繁体   English   中英

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

[英]How to order by certain columns first in a union select

我正在从各种表中执行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 ,我想先ORDER BY where u.UserType = 'Consultant' and DateAdded DESC, and then by u.UserType = 'Internal' and Price DESC and DateAdded DESC

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

你可以用case来做到这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

没有任何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不正确,样本和预期输出将非常有用。

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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