MS SQL Studio 2008 - 使用SUM选择SubQuery

时间:2012-11-29 17:11:43

标签: sql sql-server-2008-r2

使用SUM遇到此子查询的问题。该查询将总计来自特定日期范围的若干记录的利润列。我将此总利润按记录附加的帐号进行分组。使用一个帐号,它可以正常工作:

select
    [ACCOUNT ID],
    (
     select SUM(PROFIT)
     from [Transaction Table]
     where [ACCOUNT ID] in ('1001')
     and [ACTIVITY DATE] in ('5/31/2012')
    ) as 'May Profit'

from
    [Transaction Table]

where
    [ACCOUNT ID] in ('1001')

group by
    [ACCOUNT ID]    

给出正确的结果:

    | ACCOUNT ID | May Profit |
    ---------------------------
    |    1001    |   $61.97   |

麻烦来自多个帐号:

select
    [ACCOUNT ID],
    (
     select SUM(PROFIT)
     from [Transaction Table]
     where [ACCOUNT ID] in ('1001','2001')
     and [ACTIVITY DATE] in ('5/31/2012')
    ) as 'May Profit'

from
    [Transaction Table]

where
    [ACCOUNT ID] in ('1001','2001')

group by
    [ACCOUNT ID]    

结果不正确:

    | ACCOUNT ID | May Profit |
    ---------------------------
    |    1001    |  $127.34   |
    |    2001    |  $127.34   |

每个记录的两个帐户的“5月利润”总计。我需要每个帐号的个人利润总额。

有什么想法?提前谢谢!

2 个答案:

答案 0 :(得分:2)

您不需要使用子查询

 select
     [ACCOUNT ID],
     SUM(PROFIT)
 from [Transaction Table]
 where [ACCOUNT ID] in ('1001','2001') and [ACTIVITY DATE] in ('5/31/2012')
 group by [ACCOUNT ID]

您的查询只计算了两个帐户的总和,并在每行显示


更新

实际上,对于多个总和,我会做这样的事情

 select
     [ACCOUNT ID],
     SUM(case when [ACTIVITY DATE] in ('5/31/2012') then PROFIT else 0 end) as 'May Profit',
     SUM(case when [ACTIVITY DATE] in ('4/31/2012') then PROFIT else 0 end) as 'April Profit'
 from [Transaction Table]
 where [ACCOUNT ID] in ('1001','2001') and 
 group by [ACCOUNT ID]

答案 1 :(得分:0)

您不需要使用SubQuery,但是有两种方法可以执行:

第一种方式,使用您的查询(不推荐) - 注意帐户ID = T.Account Id:

select
    [ACCOUNT ID],
    (
     select SUM(PROFIT)
     from [Transaction Table]
     where [ACCOUNT ID] = T.[ACCOUNT ID]
     and [ACTIVITY DATE] in ('5/31/2012')
    ) as 'May Profit'
from
    [Transaction Table] T
where
    [ACCOUNT ID] in ('1001','2001')
group by
    [ACCOUNT ID]  

更好的方法:

select
     [ACCOUNT ID],
     SUM(PROFIT)
from [Transaction Table]
where [ACCOUNT ID] in ('1001','2001') and [ACTIVITY DATE] in ('5/31/2012')
group by [ACCOUNT ID]