I have a table with the following data:
ItemId PendingTime
1 2016-11-23 15:57:56.000
2 2016-07-09 17:33:09.000
3 2015-11-27 18:34:03.000
and so on..
I would like to know sum of items pending since last 30 mins, last 1 hr, last 1 week, last 1 month and over an year. I came up with the following query:
SELECT
SUM(CASE
WHEN datediff(MINUTE, PENDING_TIME,GETDATE()) <= 30
THEN 1 ELSE 0
END) AS '30 Min',
Sum(case when (datediff(MINUTE,PENDING_TIME, GETDATE())) > 30 AND (datediff(MINUTE,PENDING_TIME, GETDATE())) <= 60 then 1 Else 0 End) as 'Over 30 Min',
Sum(case when (datediff(MINUTE,PENDING_TIME, GETDATE())) > 60 AND (datediff(HOUR,PENDING_TIME, GETDATE())) <= 24 then 1 Else 0 End) as 'Over 1 Hr',
Sum(case when (datediff(DAY,PENDING_TIME, GETDATE())) > 1 AND (datediff(DAY,PENDING_TIME, GETDATE())) < 30 then 1 Else 0 End) as '1 month',
Sum(case when datediff(DAY,PENDING_TIME, GETDATE()) >= 30 then 1 Else 0 End) as 'More than month'
from ItemsTable where datepart(yyyy,PENDING_TIME) = DATEPART(yyyy,GETDATE())
This returns data as:
30 Min Over 30 Min Over 1 Hr 1 month More than month
----------- ----------- ----------- ----------- ---------------
100 350 NULL NULL NULL
I would like the results in 2 column format as:
30 Min ------ 45
Over 30 ------ 100
Over 1 hr ------ null
Over 1 month ------ null
I am aware of the pivot function, however the columns I have selected aren't really in the table I am selecting from, rather they are created as result of aggregate function.
How do I get this in 2 column and multiple rows format.
Thanks for reading through.