1

使用 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   |

每条记录上的两个账户的“五月利润”都在合计。我需要每个帐号的个人利润总额。

有什么想法吗?提前致谢!

4

2 回答 2

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]
于 2012-11-29T17:14:45.197 回答
0

您不需要使用子查询,但您可以通过以下两种方式来实现:

第一种方式,使用您的查询(不推荐) - 注意 Account 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]
于 2012-11-29T17:17:29.207 回答