AHungerArtist
AHungerArtist

Reputation: 9579

SQL Order by using the values from two different columns

Suppose I have a table NAME with the columns PART_TYPE and VALUE. Each type can have multiple types like FAMILY, GIVEN, PREFIX, etc.

What I would like to do is write SQL to get all the names but have them first ordered by a specific type then have them ordered alphabetically within that type.

I have something like this:

SELECT *
FROM name
ORDER BY (
  CASE
    WHEN PART_TYPE = 'GIV'
    THEN VALUE
  END)

But I'm not sure how to include the other types as a primary order while keeping the VALUE as the secondary order. Adding another case statement will then just make VALUE the primary order.

I would like to keep this database independent but if need be, I would be willing to make it Oracle specific.

How can I do this? Also, a way of doing this with Hibernate Criteria would also be greatly appreciated.

Edit: I need the PART_TYPE to be ordered by a specific order as defined by me. In particular, it needs to be GIVEN then FAMILY.

So it should look like this:

GIVEN  A
GIVEN  B
GIVEN  C
FAMILY A
FAMILY B

The natural order by would have FAMILY first, not GIVEN.

Upvotes: 2

Views: 759

Answers (4)

GarethD
GarethD

Reputation: 69769

The most manageable way of resolving this is probably to have a table containing all your Types, and then a sort column within that. So you might have a table like:

TypeID      Name      SortOrder
1           FAMILY    2
2           GIVEN     1
3           PREFIX    3

Then you Can join this on to your query and use:

ORDER BY SortOrder, Value

You could just resolve this with a CASE expression

ORDER BY CASE Type
            WHEN 'GIVEN' THEN 1
            WHEN 'FAMILY' THEN 2
            WHEN 'PREFIX' THEN 3
            END,
            Value

But the more types you have the less manageable the case expression becomes.

Upvotes: 2

David Adlington
David Adlington

Reputation: 666

Feels a bit 'hacky' but it works

SELECT part_type,name
FROM (
SELECT 
CASE 
WHEN part_type = 'Given' THEN 'A'
WHEN part_type = 'Family' THEN 'B'
END AS Sorthack,
part_type,
name
FROM NAME
) Sort

ORDER BY sorthack,name

Upvotes: 0

erikxiv
erikxiv

Reputation: 4075

SELECT *
FROM name
ORDER BY 
  CASE 
        WHEN TYPE = 'GIVEN' THEN 1
        WHEN TYPE = 'FAMILY' THEN 2
        ELSE 3
     END,
  VALUE

This will order the result by a custom order on TYPE and VALUE as the secondary order.

Upvotes: 1

zerkms
zerkms

Reputation: 254924

ORDER BY CASE TYPE
             WHEN 'GIVEN' THEN 0   
             WHEN 'FAMILY' THEN 1
             ELSE 2
         END,
         VALUE

Upvotes: 1

Related Questions