Skip to content

Instantly share code, notes, and snippets.

@codingbadger
Last active October 28, 2015 08:31
Show Gist options
  • Save codingbadger/64efba8a3d8402286635 to your computer and use it in GitHub Desktop.
Save codingbadger/64efba8a3d8402286635 to your computer and use it in GitHub Desktop.
PivotSQL_SelectOnly
/* SETUP */
Declare @ProductInfo Table
(
ProductName varchar(10),
DateOfSale datetime,
SaleValue int
);
Declare @StartDate datetime, @EndDate DateTime
Set @StartDate = '2011-05-01'
Set @EndDate = '2011-06-30'
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),
('c','2011-06-19',6),
('d','2011-06-24',4),
('b','2011-06-25',7),
('b','2011-06-29',6);
/* SETUP */
-- Generate temp cte to contain all the days within the range
-- calculate the actual week number e.g. week 20, 21, 22,23
-- Also calculate the week number within the range e.g. 1,2,3,4
With Dates as (
Select DATEADD(Day, number - 1, @StartDate) as [DateRow],
DATEPART(WEEK, DATEADD(Day, number - 1, @StartDate)) as [WeekNumber],
((DateDiff(day, @StartDate, DATEADD(Day, number - 1, @StartDate)) / 7) + 1) as [WeekSequence]
From (Select ROW_NUMBER() Over (Order By c.Object_Id) as number
From sys.columns c
)numbers
Where number -1 <= DATEDIFF(Day, @StartDate, @EndDate)
)
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 p.ProductName,
d.WeekSequence as [Weeks],
p.SaleValue
From @ProductInfo p
cross apply Dates d
-- 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 p.DateOfSale = d.DateRow
And p.DateOfSale >= @StartDate
And p.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