Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Pivot columns

Author  Topic 

crazyco
Starting Member

30 Posts

Posted - 2011-04-13 : 11:49:43
Can someone help me in displaying my query in a pivot format.

The query is:

DECLARE @startDT as varchar(10)
SET @startDT = '04/04/2011'

select staffID,
dbo.mins_to_hours(SUM(dbo.hours_to_mins([break]))) as [break],
dbo.mins_to_hours(Sum(dbo.hours_to_mins(sick))) as sick,
dbo.mins_to_hours(SUM(dbo.hours_to_mins(annualLeave))) AS annualLeave
FROM Timesheet
where date BETWEEN convert(datetime,@startDT,103) AND DateAdd(day,4,convert(datetime,@startDT,103))
group by staffID

Which displays an output of:

staffID break sick annualLeave
1 03:25 03:20 04:10


I would like it to display like:

break 03:25
sick 03:20
annualLeave 04:10

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-04-13 : 12:25:50
You likely need UNPIVOT operator rather than PIVOT, as in
DECLARE @startDT as varchar(10)
SET @startDT = '04/04/2011'

;WITH CTE AS
(
SELECT
staffID,
dbo.mins_to_hours(SUM(dbo.hours_to_mins([break]))) AS [break],
dbo.mins_to_hours(SUM(dbo.hours_to_mins(sick))) AS sick,
dbo.mins_to_hours(SUM(dbo.hours_to_mins(annualLeave))) AS annualLeave
FROM
Timesheet
WHERE
date BETWEEN CONVERT(DATETIME, @startDT, 103) AND DATEADD(DAY, 4, CONVERT(DATETIME, @startDT, 103))
GROUP BY
staffID
)
SELECT StaffId, Category, Duration
FROM A
UNPIVOT ([Duration] FOR Category IN ([break],[sick],[annualLeave]))U
Go to Top of Page

crazyco
Starting Member

30 Posts

Posted - 2011-04-14 : 04:00:36
Thanks for your help sunitabeck, this worked great.
Go to Top of Page
   

- Advertisement -