March 1, 2016

CTE and Pivot

/* Pivot to display queues horizontally */

WITH Validation AS
(
select top 100 percent
UserName, QueueName, EndDate, Count(DocumentID) AS 'QueueCount'
From ValidationGroup
Group by UserName, QueueName, EndDate
Order by UserName, QueueName
)
select * from (
select top 100 percent
UserName, QueueName, EndDate, isnull(QueueCount,0) AS 'QueueCount'
From ValidationGroup
Group by UserName, QueueName, EndDate, QueueCount
Order by UserName
) src
pivot
(
Sum(QueueCount)
for QueueName in ([Incoming,Validation,Appeal,Pending)
) p;