Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

sql server - Select SQL results grouped by weeks

I want to select data from following table group by weeks

 Date       Product Name   Sale
+----------+--------------+-----+
 14-05-11     a             2
 14-05-11     b             4 
 17-05-11     c             3
 19-05-11     a             6
 24-05-11     a             6
 29-05-11     a             6    

Let suppose today is 30-05-11

So my result should look like this.

 Product Name         First Week   Second Week  Third Week
+--------------------+------------+------------+-------------+
   a                      12            6           2
   b                       0            0           4 
   c                       0            3           0  

Will some body guide me to how to write SQL query to achieve this behavior!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this should do it..

Select 
ProductName,
WeekNumber,
sum(sale)
from
(
    SELECT 
    ProductName,
    DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
    sale
    FROM table
)
GROUP BY
ProductName,
WeekNumber

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...