Let say I have table called Transactions and have 3 following columns:
Customerid TranscationDate TransactionAmount
So I need to sum transaction amounts for each customer in different date intervals. For example, transaction amount for last 10 days, transaction amount from last 10 days to last 30 days and etc..
this is what I have tried. It work, but running time is ultimately slow.
select customerid ,SUM ( case when transactiondate > @date1 and TOPUPDATE <@date0 then transactionamount else 0 end) AS Amount_last10 ,SUM ( case when transactiondate > @date2 and TOPUPDATE <@date1 then transactionamount else 0 end) AS Amountlast10_to_last20 ,SUM ( case when transactiondate > @date1 and TOPUPDATE <@date0 then transactionamount else 0 end) AS count_last10 ,SUM ( case when transactiondate > @date2 and TOPUPDATE <@date1 then transactionamount else 0 end) AS count_last10_to_20 from TransactionData t group by customerid
For better understanding I write down what I need
Customer_id Amount_last10 Amountlast10_to_last20 count_last10 count_last10_to_20 11234 100 200 3 1
Please consider that I have many many rows, so I need make my query running time as less as possible.
Advertisement
Answer
If I understand correctly, you want conditional aggregation:
select Customerid, sum(TransactionAmount) as amount_total, sum(case when datediff(day, TransactionDate, getdate()) between 0 and 9 then TransactionAmount else 0 end) as total_0_9, sum(case when datediff(day, TransactionDate, getdate()) between 10 and 19 then TransactionAmount else 0 end) as total_10_19, . . . from Transactions t group by Customerid;
For performance, you should add a where
clause so you only aggregate the data you need. For instance, for the above two columns:
where TransactionDate >= dateadd(day, -19, convert(date, getdate())