Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering query result by list of values

Tags:

sql-server

I'm working on a sql query that is passed a list of values as a parameter, like

select * 
from ProductGroups
where GroupID in (24,12,7,14,65)

This list is constructed of relations used througout the database, and must be kept in this order.

I would like to order the results by this list. I only need the first result, but it could be the one with GroupId 7 in this case.

I can't query like

order by (24,12,7,14,65).indexOf(GroupId)

Does anyone know how to do this?

Additional info:
Building a join works and running it in the mssql query editor, but...

Due to limitiations of the software sending the query to mssql, I have to pass it to some internal query builder as 1 parameter, thus "24,12,7,14,65". And I don't know upfront how many numbers there will be in this list, could be 2, could be 20.

like image 656
Sorskoot Avatar asked Dec 02 '09 09:12

Sorskoot


People also ask

How does result of a query can be ordered?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How does ORDER BY work in SQL with multiple columns?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first. The column that is entered at first place will get sorted first and likewise.

Can subquery use ORDER BY?

An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery.


2 Answers

You can also order by on a CASE:

select * 
from ProductGroups
where GroupID in (24,12,7,14,65)
order by case GroupId 
    when 7 then 1 -- First in ordering
    when 14 then 2 -- Second
    else 3
end
like image 180
Andomar Avatar answered Oct 12 '22 20:10

Andomar


Use a table variable or temporary table with an identity column, feed in your values and join to that, e.g.

declare @rank table (
    ordering int identity(1,1)
    , number int    
    )

insert into @rank values (24)
insert into @rank values (12)
insert into @rank values (7)
insert into @rank values (14)
insert into @rank values (65)

select  pg.*
from    ProductGroups pg
left outer join 
    @rank r
on  pg.GroupId = r.number 
order by 
    r.ordering
like image 40
Unsliced Avatar answered Oct 12 '22 20:10

Unsliced