簡體   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