Last active
October 28, 2015 08:31
-
-
Save codingbadger/64efba8a3d8402286635 to your computer and use it in GitHub Desktop.
PivotSQL_SelectOnly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Declare @DatePeriod datetime | |
Set @StartDate = '2011-05-01' | |
Set @EndDate = '2011-06-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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment