2

I'm looking to add two values in one single statement and I'm currently at a loss as to how to go about this, it should be simple enough here are my statements:

 SELECT COUNT(UserModified) as SecondTally
 FROM JobAgents 
 WHERE UserModified = 1

The value above is then subtracted from this value below.

 SELECT SUM(EmailsSent) as FirstTally
 FROM JobAgentEmails
 WHERE Date BETWEEN '7/1/2012 12:00:00 AM' AND '7/31/2012 11:59:59 PM'

Any help with this would be greatly appreciated. Thanks a bunch.

4

4 に答える 4

3

最も簡単な方法は、結果を 2 つのサブクエリと単純に結合することです。これらのサブクエリは、変数に格納するか、以下に示すように単一のクエリに結合することができます。

SELECT
  (SELECT SUM(EmailsSent) as FirstTally
   FROM JobAgentEmails
   WHERE Date BETWEEN '7/1/2012 12:00:00 AM' AND '7/31/2012 11:59:59 PM')
- (SELECT COUNT(UserModified) as SecondTally
   FROM JobAgents 
   WHERE UserModified = 1)
于 2012-08-27T18:55:15.807 に答える
2

これを行うには、クロス ジョインを使用して値をまとめます。

select jae.FirstTallyl - ja.SecondTally
from (SELECT COUNT(UserModified) as SecondTally
      FROM JobAgents
      WHERE UserModified = 1
     ) ja cross join
     (SELECT SUM(EmailsSent) as FirstTally
      FROM JobAgentEmails
      WHERE Date BETWEEN '7/1/2012 12:00:00 AM' AND '7/31/2012 11:59:59 PM'  
    ) jae
于 2012-08-27T18:56:29.123 に答える
1

1 つの方法を次に示します。

DECLARE @FirstTally int;
DECLARE @SecondTally int;

SELECT @SecondTally = COUNT(UserModified) 
 FROM JobAgents 
 WHERE UserModified = 1

 SELECT @FirstTally = SUM(EmailsSent) 
 FROM JobAgentEmails
 WHERE Date BETWEEN '7/1/2012 12:00:00 AM' AND '7/31/2012 11:59:59 PM'


SELECT @FirstTalley - @SecondTalley AS Result   
于 2012-08-27T18:55:24.700 に答える
1
 select 
 (SELECT SUM(EmailsSent) as FirstTally
 FROM JobAgentEmails
 WHERE Date BETWEEN '7/1/2012 12:00:00 AM' AND '7/31/2012 11:59:59 PM')
 -

 (SELECT COUNT(UserModified) as SecondTally
 FROM JobAgents 
 WHERE UserModified = 1)

 AS 'result';
于 2012-08-27T18:56:44.770 に答える