SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Grouping
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

srikanthk
Starting Member

2 Posts

Posted - 11/03/2012 :  03:01:36  Show Profile  Reply with Quote
Hello every one,

Myself srikanth, very new to sql server programming. i am using SQL Server 2005. I need help on grouping the data present in a column using SQL.

Example:
Time in Minutes
10
15
16
20
23
24
30
31
I need to put above mentioned data as following form

Result:

Range (Num)
<10 (0)
10-20 (4)
20-30 (3)
>30 (1)

Regards,
srikanth

sunitabeck
Flowing Fount of Yak Knowledge

5155 Posts

Posted - 11/03/2012 :  08:29:52  Show Profile  Reply with Quote
Should be able to do with something like this:
SELECT
	CASE 
		WHEN col1 < 10 THEN CAST('<10' AS VARCHAR(10))
		WHEN col1 < 20 THEN '10-20'
		WHEN col1 < 30 THEN '20-30'
		ELSE '>30'
	END AS [Range],
	COUNT(*) AS [Num]
FROM
	YourTable
GROUP BY
	CASE 
		WHEN col1 < 10 THEN CAST('<10' AS VARCHAR(10))
		WHEN col1 < 20 THEN '10-20'
		WHEN col1 < 30 THEN '20-30'
		ELSE '>30'
	END
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 11/03/2012 :  21:47:25  Show Profile  Reply with Quote
i would prefer putting ranges into a table of its own with boundary values so that it would be maintainable moving forward. This will give you ability to redefine ranges and add/remove ranges by means of DML statements to table rather than changing CASE WHEN inside procedure each time. The procedure will just have a join to this table on condition like

...
ON value BETWEEN startval AND endval
..


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

srikanthk
Starting Member

2 Posts

Posted - 11/04/2012 :  23:31:37  Show Profile  Reply with Quote
@sunitabeck, Thank you for replying. code is working perfectly.
@visakh16, Thank you for suggetion.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000