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
/* SETUP */ | |
Declare @ProductInfo Table | |
( | |
ProductName varchar(10), | |
DateOfSale datetime, | |
SaleValue int | |
); | |
Insert Into @ProductInfo | |
Values ('a','2011-05-14',2), | |
('b','2011-05-14',4), | |
('c','2011-05-17',3), | |
('a','2011-05-19',6), | |
('a','2011-05-24',4), | |
('a','2011-05-25',7), | |
('a','2011-05-29',6); | |
/* SETUP */ | |
Declare @StartDate datetime, @EndDate 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', | |
IsNull([6], 0) as 'Week 6', | |
IsNull([7], 0) as 'Week 7', | |
IsNull([8], 0) as 'Week 8', | |
IsNull([9], 0) as 'Week 9' | |
From | |
( | |
Select ProductName, | |
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, DateOfSale), 0), DateOfSale) +1 as [Weeks], | |
SaleValue | |
From @ProductInfo | |
-- 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 DateOfSale >= @StartDate | |
And DateOfSale <= @EndDate | |
)p | |
Pivot (Sum(SaleValue) for Weeks in ([1],[2],[3],[4],[5],[6],[7],[8],[9])) as pv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment