如何在联合选择中首先按某些列排序

时间:2017-12-01 12:44:36

标签: sql sql-server tsql sql-server-2012 sql-server-2014

我正在从各个表中执行SELECT语句,但我想首先ORDER BY一组标准。以下是SELECT语句的示例:

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

从上面的结果集中,我想先ORDER BY where u.UserType = 'Consultant' and DateAdded DESC, and then by u.UserType = 'Internal' and Price DESC and DateAdded DESC

我怎样才能以上述方式强制排序

3 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:1)

没有要测试的任何DDL和Sample数据,这是一个猜测,但也许......

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

编辑,重读后,我并不完全确定这是OP想要的。如果我和Magnus不正确,样本和预期输出将非常有用。

答案 2 :(得分:1)

顾问是否先订购。然后按价格订购(但不是顾问,所以他们按固定的伪价格订购)。然后按日期排序。

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

首先是顾问(按日期排序),其次是所有其他顾问(按价格和日期排序)。

如果存在的用户类型多于您提到的两个用户类型,而您首先需要顾问,那么其他人则需要更改第一个订单行:

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;