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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...