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
 Help needed - sorting

Author  Topic 

groston
Yak Posting Veteran

61 Posts

Posted - 2013-03-23 : 00:47:27
I have a SQL table whose data looks like this:

Parm1 Parm2
V1 V11
V1 V12
V2 V21
V2 V22
V3 V31
V3 V32

I would like to sort the table, based on a parameter, in the following manner. If the parameter is V1, the table will appear as above. If the parameter is V2, the table will be sorted like this:

Parm1 Parm2
V2 V21
V2 V22
V1 V11
V1 V12
V3 V31
V3 V32

And, if the parameter is V3, the table will be sorted like this:

Parm1 Parm2
V3 V31
V3 V32
V1 V11
V1 V12
V2 V21
V2 V22

I have figured out how to make the rows associated with the parameter appear first:

SELECT *
FROM (
SELECT 1 AS sv, * FROM myTable WHERE Parm1 = @Parm1value
UNION
SELECT 2 AS sv, * FROM myTable WHERE Parm1 <> @Parm1value
) dt
ORDER BY sv

but I cannot then sort the other rows. Can you please offer some guidance.

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2013-03-23 : 01:27:04
ORDER BY sv, CONVERT(INT, REPLACE(Parm1, 'V', ''))
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2013-03-23 : 04:35:55
[code]ORDER BY CASE WHEN Parm1 = @UserParameter THEN 0 ELSE 1 END, Parm1, Parm2[/code]


N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

nurunseo
Starting Member

6 Posts

Posted - 2013-03-24 : 02:07:05
Hi guys !
I am also new in this forum.
I wanna know in about of this forum...............

http://paneuromix.com/en
http://paneuromix.com/nootropics.html
Go to Top of Page

groston
Yak Posting Veteran

61 Posts

Posted - 2013-03-24 : 21:27:01
russell,

Thank you for replying. You took my example too literally - my bad for not being clearer.

SwePeso,

You suggestion works perfectly. Thank you for pointing out the ORDER BY CASE construct to me.
Go to Top of Page
   

- Advertisement -