Wednesday, March 21, 2012

Order By "IN"

SELECT DISTINCT * FROM Products WHERE ProductID
IN(1406,761,587,646,182)
I need to Order by the "IN"
1. 1406
2. 761
3. 587
4. 646
5. 182
Does anyone know how to do that?
From
MikeIf you use the method of a separate table, and parsing by the order the
commas are found, then you could add an identity column to the table and
order by that first.
http://www.aspfaq.com/2248
"AspMike" <mike@.pwim.com> wrote in message
news:1145898945.787474.170770@.j33g2000cwa.googlegroups.com...
> SELECT DISTINCT * FROM Products WHERE ProductID
> IN(1406,761,587,646,182)
> I need to Order by the "IN"
> 1. 1406
> 2. 761
> 3. 587
> 4. 646
> 5. 182
> Does anyone know how to do that?
> From
> Mike
>|||If this is generally a big list, a reasonable approach is to maintain a
table/ derived table of such values & use a sort column accordingly. For
shorter lists, you can either use CASE like:
ORDER BY CASE product_id WHEN 1406 THEN 1
WHEN 761 THEN 2
WHEN 587 THEN 3
WHEN 646 THEN 4
WHEN 182 THEN 5
ELSE 6
END
Or use PATINDEX or CHARINDEX string functions like:
ORDER BY CHARINDEX ( ',' + CAST( product_id AS VARCHAR ) + ',',
',1406,761,587,646,182,' )
Anith|||Unh? the IN(<list> ) is a set (actually a table value constructor)
and has no ordering by definition. Let me repeat that BY DEFINITION.
In English and with sample output, what are you trying to do?

No comments:

Post a Comment