I have table where I am having sales data for each day.
| Date | Sales |
| ------------ | ------------ |
| 3/1/2023 | 800 |
| 3/2/2023 | 300 |
| 3/3/2023 | 500 |
| 4/1/2023 | 300 |
| 4/2/2023 | 500 |
| 4/3/2023 | 200 |
| 5/1/2023 | 100 |
| 5/2/2023 | 400 |
| 5/3/2023 | 400 |
Expected Output:
Date | Sales | Diff |
---|---|---|
5/1/2023 | 900 | 100 |
4/1/2023 | 1000 | 600 |
3/1/2023 | 1600 | 0 |
I created a query to get sales sum for each month and I need to calculate difference between previous month and next month:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, Salesdate), 0) AS TrendStartDate,
SUM(Sales) AS TotalSales ,
LEAD(SUM(Sales), 1) OVER (PARTITION BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Salesdate), 0)
ORDER BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Salesdate), 0) DESC) AS Sales_diff
FROM salestable
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Salesdate), 0)
ORDER BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Salesdate), 0) ASC
Could any one please help on this?
2条答案
按热度按时间pbgvytdp1#
You can apply a simple aggregation first, and aggregate:
Then you can use the
LAG
window function to gather your previous sum of sales.The last
ORDER BY
is not needed, it's just for visualization purposes.Output:
| Date | TotalSales | Diff |
| ------------ | ------------ | ------------ |
| 2023-05-01 | 900 | 100 |
| 2023-04-01 | 1000 | 600 |
| 2023-03-01 | 1600 | 0 |
Check the demo here .
mnemlml82#
You can do it by applying the
LAG
function to only the rows with totals as follows :First we need to get totals per month using :
Then apply the analytic function
LAG()
to this dataset to get difference:Demo here