SQL sum () at different periods?

I am working on a stored procedure. I have a table called #CashFlow that contains data for a period of time.

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

I also have a table called #Funds that contains a list of fund identifier that interests me. (There is a bunch of processing that I won’t bore you that generates this list of funds for me) For example, suppose that in my table #Funds there are only IDs 1 and 2 (3 is excluded).

I have three time periods (all ended on "8/31/2010") from 01/01/2004, 1/1/2006 and 1/1/2010, and I would like to combine the amount of three periods.

I tried something like this:

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'

, ( , ). , , , ou.

, :

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'

, - ( )

+3
2
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
+5

:

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

Source: https://habr.com/ru/post/1773617/


All Articles