Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language:
Expertise: Beginner
Dec 14, 2001

Conditional Sorting in T-SQL


There may be certain situations where you have to sort character-based columns in a particular order.

For example, Let us consider a table:
 
--///////////////////////////////////

SID	Subject		Marks
---	------		-----
1	Physics		80
1	Chemistry	75
1	Maths		90
1	Biology		70
2	Physics		65
2	Chemistry	70
2	Maths		80
2	Biology		60
--///////////////////////////////////

Now you are asked to query a table in such a manner that Maths should come first, Physics second, Chemistry third, and Biology last for each StudentID.

To accomplish this, use T-SQL "Case" statement:
 
--///////////////////////////////////
select tblMarks.*
from tblMarks  order by SID,
	(case Subject
		when 'Maths' then 1
		when 'Physics' then 2
		when 'Chemistry' then 3
		when 'Biology' then 4
		end ) asc


SID	Subject		Marks
---	------		-----
1	Maths		90
1	Physics		80
1	Chemistry	75
1	Biology		70
2	Maths		80
2	Physics		65
2	Chemistry	70
2	Biology		60

--///////////////////////////////////
Harinatha Reddy
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date