在 SELECT SQL 中设置新字段优先级

Set new field priority in SELECT SQL

我有 table 个具有以下结构的帐单:

id | store_name | sum | payment_date
1  | Amazon     | 10  | 11.05.2022
2  | Amazon     | 20  | 11.05.2022
3  | Ebay       | 15  | 11.05.2022
4  | AppleStore | 13  | 11.05.2022
5  | Google Play| 6   | 11.05.2022

我需要的是 select 来自 table 的所有数据,并根据账单金额设置附加字段“优先级”。前 2 行获得优先级 1,接下来的 2 行获得优先级 2,其他获得 0:

id | store_name | sum | payment_date | priority
2  | Amazon     | 20  | 11.05.2022   | 1
3  | Ebay       | 15  | 11.05.2022   | 1
4  | AppleStore | 13  | 11.05.2022   | 2
1  | Amazon     | 10  | 11.05.2022   | 2
5  | Google Play| 6   | 11.05.2022   | 0

此外 table 包含不同日期的账单数据(字段 payment_date),应根据每一天的数据设置此优先级。

对每一天的行进行排序,然后根据行号分配优先级:

SELECT t.*,
       CASE ROW_NUMBER()
              OVER (PARTITION BY TRUNC(payment_date) ORDER BY sum DESC)
       WHEN 1 THEN 1
       WHEN 2 THEN 1
       WHEN 3 THEN 2
       WHEN 4 THEN 2
       ELSE 0
       END AS priority
FROM   table_name t

其中,对于示例数据:

CREATE TABLE table_name (id, store_name, sum, payment_date) AS
SELECT 1, 'Amazon',      10, DATE '2022-05-11' FROM DUAL UNION ALL
SELECT 2, 'Amazon',      20, DATE '2022-05-11' FROM DUAL UNION ALL
SELECT 3, 'Ebay',        15, DATE '2022-05-11' FROM DUAL UNION ALL
SELECT 4, 'Apple Store', 13, DATE '2022-05-11' FROM DUAL UNION ALL
SELECT 5, 'Google Play',  6, DATE '2022-05-11' FROM DUAL;

输出:

ID STORE_NAME SUM PAYMENT_DATE PRIORITY
2 Amazon 20 2022-05-11 00:00:00 1
3 Ebay 15 2022-05-11 00:00:00 1
4 Apple Store 13 2022-05-11 00:00:00 2
1 Amazon 10 2022-05-11 00:00:00 2
5 Google Play 6 2022-05-11 00:00:00 0

db<>fiddle here