繁体   English   中英

如何在 SQL 中插入新列基于 Window Function 排名和条件

[英]How to Insert a new Column in SQL based on Window Function Ranking and Condition

在下表中,“排名”是使用RANK() function 实现的,类似于:

RANK() OVER(PARTITION BY month, year) as ranking
汽车类型 model 销售量 排行
4 2020 奔驰 s_class 2000 1
5 2020 奔驰 s_class 1500 2
10 2020 宝马 x5 7000 1
11 2020 宝马 x5 6000 2
12 2020 宝马 x5 5000 3

期望的结果是创建一个特征,例如' best_sales_month ',这将等于'month' 列的数量,其中'ranking'=1对于每个不同的'car_type' 和'model' 对 它看起来像这样:

汽车类型 model 销售量 排行 best_sales_month
4 2020 奔驰 s_class 2000 1 4
5 2020 奔驰 s_class 1500 2 4
10 2020 宝马 x5 7000 1 10
11 2020 宝马 x5 6000 2 10
12 2020 宝马 x5 5000 3 10

例如,对于 BMW x5 汽车,'best_sales_month' 为 10,因为当月 = 10 时,该对 car_type 和 model 的销售额更大。

目前,我已经达到了这一点:

CASE 
  -- when ranking=1, grab the value of 'month' for that entry:
  WHEN ranking =1 THEN month 
  -- how to populate that number to the rest of the car_type & model pairs?
END AS best_sales_month 

最后是这样的:

汽车类型 model 销售量 排行 best_sales_month
4 2020 奔驰 s_class 2000 1 4
5 2020 奔驰 s_class 1500 2 NULL
10 2020 宝马 x5 7000 1 10
11 2020 宝马 x5 6000 2 NULL
12 2020 宝马 x5 5000 3 NULL

所以本质上,当'ranking'=1 时,如何为每个 car_type 和 model 对填充 NULL 值行与 'month' 值?

提前致谢!

您可以使用first_value(expr)分析 function 根据分析子句中提供的顺序获取表达式expr的第一个值:

 with input_tab(month, year, car_type, model, sales, ranking) as ( select 4, 2020, 'mercedes', 's_class', 2000, 1 union all select 5, 2020, 'mercedes', 's_class', 1500, 2 union all select 10, 2020, 'bmw', 'x5', 7000, 1 union all select 11, 2020, 'bmw', 'x5', 6000, 2 union all select 12, 2020, 'bmw', 'x5', 5000, 3 ) select *, first_value(month) over(partition by year, car_type, model order by sales desc) as best_sales_mon from input_tab
 月 | 年份 | 汽车类型 |  model | 销售 | 排名 |  best_sales_mon ----: |  ---: |:------- |:------ |  ----: |  ------: |  -------------: 10 |  2020 | 宝马 |  x5 |  7000 |  1 |  10 11 |  2020 | 宝马 |  x5 |  6000 |  2 |  10 12 |  2020 | 宝马 |  x5 |  5000 |  3 |  10 4 |  2020 | 梅赛德斯|  s_class |  2000 |  1 |  4 5 |  2020 | 梅赛德斯|  s_class |  1500 |  2 |  4

请注意,大多数现代 DBMS 都是一样的,所以我将 Postgres 用于db<>fiddle

暂无
暂无

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

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