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
 Grouping results in T-SQL

Author  Topic 

ArnoldG
Starting Member

36 Posts

Posted - 2013-10-09 : 09:20:55
Hello,

I am having a question about creating a T-SQL query:

The basic query is this:

SELECT
Fullname
,datediff(minute,rq.realized, rq.processed)/60.0 AS hours
FROM
requests


However, I need to get the amount of hours in four groups (0-24, 25-48, 49-72, >72).

So it should look like this:

Fullname 0-24 25-48 49-72 >72
Name1
Name2
Name3

How do I do this ?

Thanks for your help,
Arnold

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-10-09 : 11:38:50
One way is to use CASE expressions:
SELECT
FullName,
CASE WHEN [Hours] BETWEEN 0 AND 24 THEN 1 ELSE 0 END AS [0-24].
CASE WHEN [Hours] BETWEEN 25 AND 48 THEN 1 ELSE 0 END AS [25-48],
CASE WHEN [Hours] BETWEEN 49 AND 72 THEN 1 ELSE 0 END AS [49-72],
CASE WHEN [Hours] > 72 THEN 1 ELSE 0 END AS [>72]
FROM
(
SELECT
Fullname
,datediff(minute,rq.realized, rq.processed)/60.0 AS hours
FROM
requests
) AS T
You didn't way how you waned your output, so I just made those range columns into flags.
Go to Top of Page

ArnoldG
Starting Member

36 Posts

Posted - 2013-10-09 : 11:44:15
Thanks a lot !
This works perfect,
Arnold
Go to Top of Page
   

- Advertisement -