Postgresql

如何根據條件縮小 SQL 中的記錄範圍

  • August 17, 2018
Customer   Rank      Joining_date       salary
   A         2        2017-10-12         500
   A         1        2017-10-10         800     
   A         1        2017-10-20         400
   B         2        2017-05-20         200
   B         2        2017-05-15         100
   c         3        2017-06-10         600
   c         4        2017-06-05         600

邏輯:對於給定的客戶

如果 Rank 為 1 ,則保留所有排名為 1 的記錄並刪除其餘記錄

如果客戶有不同等級的記錄,則根據最新等級選擇記錄(按等級降序排列)並刪除另一個

如果客戶有相同等級的記錄(不是1),則根據最低工資選擇記錄(按工資升序排列)**

預期結果

Customer   Rank      Joining_date       salary
   A         1        2017-10-10         800     
   A         1        2017-10-20         400
   B         2        2017-05-15         100
   c         4        2017-06-05         600

排名 1 的客戶和其他客戶的行為不同,因此只需使用不同的查詢。最後兩個邏輯條件可以通過每個客戶的簡單 ORDER BY 來計算;將該訂單與整行相關聯需要一個視窗函式:

WITH Rank1Customers AS (
 SELECT DISTINCT Customer
 FROM MyTable
 WHERE Rank = 1
)

SELECT Customer, Rank, Joining_date, Salary
FROM MyTable
WHERE Customer IN (TABLE Rank1Customers)
 AND Rank = 1

UNION ALL

SELECT Customer, Rank, Joining_date, Salary
FROM (SELECT *,
            row_number() OVER (PARTITION BY Customer
                               ORDER BY Rank DESC, Salary ASC) AS OrderNr
     FROM MyTable
     WHERE Customer NOT IN (TABLE Rank1Customers)
    ) AS _
WHERE OrderNr = 1;

SQL 小提琴

引用自:https://dba.stackexchange.com/questions/215041