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!
How Do You Group Data by Week in SQL Server? SQL Server provides a function called DATEPART() , which returns a specified part (year, quarter, month, week, hour, minute, etc.) of a specified date. ORDER BY DATEPART(week, RegistrationDate);
The WEEK() function returns the week number for a given date (a number from 0 to 53).
Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.
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
the provided solutions seem a little complex? this might help:
https://msdn.microsoft.com/en-us/library/ms174420.aspx
select
mystuff,
DATEPART ( year, MyDateColumn ) as yearnr,
DATEPART ( week, MyDateColumn ) as weeknr
from mytable
group by ...etc
This should do it for you:
Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'
Select ProductName,
IsNull([1],0) as 'Week 1',
IsNull([2],0) as 'Week 2',
IsNull([3],0) as 'Week 3',
IsNull([4],0) as 'Week 4',
IsNull([5], 0) as 'Week 5'
From
(
Select ProductName,
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
Sale as 'Sale'
From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv
It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod
variable is used to fetch only rows relative to the month (in this example only for the month of May)
Output using my sample data:
Base on @increddibelly answer, I applied to my query as below.
I share for whom concerned.
My table structure FamilyData(Id, nodeTime, totalEnergy)
select
sum(totalEnergy) as TotalEnergy,
DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With