0

I need to query a table and get the records back in a complex scheme of ordering.

I can get the results I want with 3 separate queries and then concatenate the results by brute force after retrieval with my programming code.

I would rather get everything back with one call to the database, with one database.

I have a table called "committee" listing committee names and subcommittee names.

committee_name               subcomittee_name
--------------               -----------------
Hals Committee on Books
Hals Committee on Books      Subcommittee on Paperbacks
Hals Committee on Books      Subcommittee on Leather Bound Volumes
General Purpose Committee
Stans Committee on Music
Stans Committee on Music     Subcommittee on CDs
Stans Committee on Music     Subcommittee on MP3s

Every subcommittee belongs to a parent committee.

Not all committees have a subcommittee.

Every committee will have a null entry for subcommittee to distinguish a new/different committee

I would like to get all of the committee and subcommittee names back, sorted in ascending order, but with a twist. I would like all of "Stans" committees listed first, then Hals and then the others.

Example:

committee_name               subcomittee_name
--------------               -----------------
Stans Committee on Music
Stans Committee on Music     Subcommittee on CDs
Stans Committee on Music     Subcommittee on MP3s
Hals Committee on Books
Hals Committee on Books      Subcommittee on Paperbacks
Hals Committee on Books      Subcommittee on Leather Bound Volumes
General Purpose Committee

I can get that with 3 separate queries:

select * from committee where substr(committee_name,1,1) = 'S' order by committee_name,subcommittee_name nulls first

select * from committee where substr(committee_name,1,1) = 'H' order by committee_name,subcommittee_name nulls first

select * from committee where substr(committee_name,1,1) not in ('H','S') order by committee_name,subcommittee_name nulls first

What I would like is to get what I want with just 1 query, 1 trip to the database.

Any ideas?

Steve

4

1 回答 1

4

您可以先使用 acase来订购“S”,然后是“H”,然后是其他字母:

select  committee_name
,       subcommittee_name 
from    committee 
group by 
        committee_name
,       subcommittee_name
order by
        case min(substring(comittee_name,1,1))
        when 'S' then 1
        when 'H' then 2
        else 3
        end
,       committee_name
,       subcommittee_name nulls first

聚合是必需的min,因为您可能会对整组行进行排序。

于 2013-02-21T18:03:34.927 回答