不同时期的SQL sum()?

时间:2010-11-08 13:43:28

标签: sql sql-server-2000 aggregate

我正在处理存储过程。我有一个名为#CashFlow的表,其中包含一段时间的数据。

FundID   TradeDate Amount 
 1       1/1/2004  123.00 
 1       6/30/2006 100.00 
 2       1/1/2004  100.00 
 2       3/15/2010 150.00
 3       1/1/2010  100.00

我还有一个名为#Funds的表,其中包含我感兴趣的基金ID列表。(有一些我不会厌烦的处理,为我生成这个基金列表)例如,我只想说我的#Funds表中只有ID为1和2(不包括3个)。

我有三个时间段(所有结束时间为'8/31/2010'),从2004年1月1日,2006年1月1日和2010年1月1日开始,我想汇总总和三个时期。

我尝试过这样的事情:

select sum(c1.amount), sum(c2.amount), sum(c3.amount)
from 
    #fundtable f
inner join
    #cashflow c1 on f.fundid = c1.fundid and c1.tradedate between '1/1/2004' and '8/31/2010'
inner join
    #cashflow c2 on f.fundid = c2.fundid and c2.tradedate between '1/1/2006' and '8/31/2010'
inner join 
    #cashflow c3 on f.fundid = c3.fundid and c3.tradedate between '1/1/2010' and '8/31/2010'

但它没有做我想要的事情(实际上我无法弄清楚它到底在做什么)。如果我只选择一个句点,我会得到正确的值,但是第二个我添加了一个联接,我的数字全部被打破了。

这就像我想要替换的原始查询:

select 
   (select sum(Amount) from #Cashflow c inner join #fundtable f on c.fundid = f.fundid where tradedate between '1/1/2004' and '8/31/2010') as 'Period1',
   (select sum(Amount) from #Cashflow c inner join #fundtable f on c.fundid = f.fundid where tradedate between '1/1/2006' and '8/31/2010') as 'Period2',
   (select sum(Amount) from #Cashflow c inner join #fundtable f on c.fundid = f.fundid where tradedate between '1/1/2010' and '8/31/2010') as 'Period3'

请注意,我的日期实际上是变量(对此而言无关紧要)和我的原始查询

2 个答案:

答案 0 :(得分:6)

SELECT  SUM(CASE WHEN TradeDate BETWEEN '2004-01-01' AND '2010-08-31' THEN Amount END),
        SUM(CASE WHEN TradeDate BETWEEN '2006-01-01' AND '2010-08-31' THEN Amount END),
        SUM(CASE WHEN TradeDate BETWEEN '2010-01-01' AND '2010-08-31' THEN Amount END)
FROM    Funds
JOIN    Cashflow
ON      Cashflow.id = Funds.id

答案 1 :(得分:2)

使用group by:

select period, sum(money) from table group by period