我正在处理存储过程。我有一个名为#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'
请注意,我的日期实际上是变量(对此不重要)和原始查询
最佳答案
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