Groups | Blog | Home
all groups > sql server new users > february 2005 >

sql server new users : Order by query question



James Hancock
2/10/2005 5:43:46 PM
Ok, this is stupid, I know I should know this but...

I've got the following

SELECT ID, Name + ': ' + SerialNo AS Name FROM Products ORDER BY Name

This always orders by the Products.Name field. I notice that if I change
the AS Name to something that isn't in the Products table and change the
Order by accordingly, it will then sort on that created field.

My question is, given that there are cases where I can't just use a unique
name for the concatenated field, how do I sort on the concatentated field
explicitly instead of on the Products.Name?

Thanks!
James Hancock

Geert Vanhove
2/11/2005 1:21:01 AM
Maybe the syntax looks not that flashy but it works:
SELECT ID, Name + ': ' + SerialNo FROM Products
ORDER BY Name + ': ' + SerialNo



[quoted text, click to view]
James Hancock
2/11/2005 11:25:45 PM
Ugh.... that's nasty syntax to use... Makes it really hard to maintain the
query because if you make a change to the select you also have to make a
change to the order by...

But hey, it works... anyone have a better way? I can't believe that they
left this out...

James Hancock

[quoted text, click to view]

Walter Clayton
2/12/2005 10:50:59 PM
Derived table.

select *
from
(
select id as id
, name + ':' + SerialNo as sort_key
from products
) d_t
order by d_t.sort_key
;

--
Walter Clayton
Any technology distinguishable from magic is insufficiently advanced.


[quoted text, click to view]
DQ
2/14/2005 12:37:08 PM
James,

The simplest way to get this working is just use the column number:

Order 2

That means you sort on the second column on your selected column list. That
always works better when you have a complicated column list as using case
statement.

Cheers,

Roger

[quoted text, click to view]
James Hancock
2/14/2005 4:33:19 PM
Thanks! That works nicely!

They really should have some sort of syntax for this...

[quoted text, click to view]

AddThis Social Bookmark Button