Search code examples
sql-serversql-server-2008pivotcrosstabdynamic-pivot

How do I order weekdays with row and column total in dynamic pivot


I have a table in which I have some Employee details like id,employeeid,workdate,taskid,hours,entrydate,entryby

And the other table have the basic information about user like firstname,lastname,emailid,password

now I want to create a crosstab query in which I want to display username and the weekday and the working total hours of the employee. well first i was thinking to use temp table for this But I failed to do so I use something like this for each day of week

select distinct employeeid ,sum(hours) as TotalHours ,'MONDAY' as Day into #Monday from Project_TimeSheet where  year(entrydate)='2014' and month(entrydate)='12' and datename(dw,entrydate)='MONDAY' group by employeeid

But for me this is not working. Anybody please tell me the query for this using pivot I want the result something like thisenter image description here


Solution

  • SELECT employeeid,
    SUM(CASE WHEN datename(dw,entrydate)='MONDAY' THEN hours END) as Monday,
    SUM(CASE WHEN datename(dw,entrydate)='TUESDAY' THEN hours END) as Tuesday,
    .....,
    sum(hours) as TotalHours
    FROM Project_TimeSheet
    WHERE  year(entrydate)='2014' and month(entrydate)='12'
    GROUP BY employeeid
    WITH ROLLUP