简体   繁体   中英

How to order by certain columns first in a union select

I am doing a SELECT statement from various tables, but I want to ORDER BY a set of criteria first. Here is an example of the SELECT statement:

SELECT
 a.ItemName,
 a.ItemDescription,
 a.ItemPrice,
 a.DateAdded,
 a.UserID,
 u.UserType
FROM
 table a
 inner join user u ON
 u.UserID = a.UserID
UNION
SELECT
 b.ItemName,
 b.ItemDescription,
 b.ItemPrice,
 b.DateAdded,
 b.UserID,
 u.UserType
FROM
 table b
 inner join user u ON
 u.UserID = b.UserID
UNION
SELECT
 c.ItemName,
 c.ItemDescription,
 c.ItemPrice,
 c.DateAdded,
 c.UserID,
 u.UserType
FROM
 table c
inner join user u ON
u.UserID = c.UserID

From the above resultset, I would like to first ORDER BY where u.UserType = 'Consultant' and DateAdded DESC, and then by u.UserType = 'Internal' and Price DESC and DateAdded DESC .

How could I force the sorting in the above manner?

You can do this using case

Order by
       case when u.UserType = 'Consultant' then 1 else 0 end,
       DateAdded desc,
       case when u.UserType = 'Internal' then 1 else 0 end,
       Price desc,
       DateAdded desc

Without any DDL and Sample data to test on, this is a bit of a guess, but perhaps...

ORDER BY CASE UserType WHEN 'Consultant' THEN 1 END DESC,
         DateAdded DESC,
         CASE UserType WHEN 'Internal' THEN 1 END DESC,
         Price DESC,
         DateAdded DESC;

Edit, upon rereading, I'm not entirely sure this is what the OP wants. Sample and expected output would be useful if myself and Magnus are incorrect.

First order by consultant or not. Then order by price (but not for consultants, so for them order by a constant pseudo price). Then order by date added.

order by
  case when usertype = 'Consultant' then 1 else 2 end,
  case when usertype = 'Consultant' then 0 else price end desc,
  dateadded desc;

This has consultants first (ordered by date added), followed by all others (ordered by price and date added).

If there exist more user types than just the two you have mentioned and you want consultants first, then internals, then others, you'd have to change the first order line accordingly:

order by
  case usertype when 'Consultant' then 1 when 'Internal' then 2 else 3 end,
  case when usertype = 'Consultant' then 0 else price end desc,
  dateadded desc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM