Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I want to create a query to summarize sales for each of the last five weeks and group by product type ie.select product, sum(amount this week), sum of (amount last week) ... group by productmy sales table looks like thisproduct date amountx d1 xxx d2 xx y d3 xxy d4 xxx d5 xxHow can this be done?thanks
nricardo
Starting Member
17 Posts
Posted - 2004-01-16 : 13:51:20
select product,sum(case when datediff(week, date, getdate()) = 0 then amount else $0.00 end) as "this_week",sum(case when datediff(week, date, getdate()) = 1 then amount else $0.00 end) as "last_week",...group by product
tkizer
Almighty SQL Goddess
38200 Posts
Posted - 2004-01-16 : 13:56:02
Here's my crack at it:
SELECT DISTINCT s1.product, week1, week2FROM sales s1INNER JOIN ( SELECT product, SUM(amount) AS week1 FROM sales WHERE [date] BETWEEN GETDATE() - 7 and GETDATE() GROUP BY product) s2ON s1.product = s2.productINNER JOIN ( SELECT product, SUM(amount) AS week2 FROM sales WHERE [date] BETWEEN GETDATE() - 14 and GETDATE() - 7 GROUP BY product) s3ON s1.product = s3.product...