Mosab Sasi Mosab Sasi - 1 month ago 11
SQL Question

Using PIVOT on column with date or datetime values

Here is my PIVOT query:

select * from t_interview_data
pivot (avg (widgets) for
datestamp in ( [2009-11-01],[2009-11-02],[2009-11-03],[2009-11-04],[2009-11-05],[2009-11-06],[2009- 11-07]
,[2009-11-08],[2009-11-09],[2009-11-10],[2009-11-11],[2009-11-12],[2009-11-13],[2009-11-14],[2009- 11-15]
,[2009-11-16],[2009-11-17],[2009-11-18],[2009-11-19],[2009-11-20],[2009-11-21],[2009-11-22],[2009-11-23]
,[2009-11-24],[2009-11-25],[2009-11-26],[2009-11-27],[2009-11-28],[2009-11-29],[2009-11-30],[2009-12-01]
,[2009-12-02])) as AvgWidgetsPerDayPerEmp


My question is this: Although this query works, is there a more easier, simpler, more elegant way to write this?

Sample output:


Answer

You can build the query and execute. Please check:

DECLARE @startdt DATETIME, @enddt DATETIME, @QueryCol NVARCHAR(MAX)

SET @startdt = '2009-11-01'
SET @enddt = '2009-12-02'

WHILE @startdt <= @enddt
BEGIN
    SET @QueryCol=isnull(@QueryCol, '')+QUOTENAME(convert(nvarchar(20), @startdt, 101))+(CASE WHEN @startdt<>@enddt THEN ',' ELSE '' END)
    SET @startdt =  @startdt + 1
END

if(ISNULL(@QueryCol, '')<>'')
begin
    set @QueryCol='select * from t_interview_data
                    pivot (avg (widgets) for 
                    datestamp in ('+@QueryCol+')) as AvgWidgetsPerDayPerEmp'

    exec (@QueryCol)
end