[英]SQL Set value for all records within a group
我想使用 CASE 语句来创建另一个列,如果该组中只有一个 Gold 出现,则该列将组中“Type”列的值设置为 Gold。
我尝试使用带有 LAG 和 LEAD 的 CASE 语句来检查 Type = 'Gold' 中的上一行或下一行,但结果证明这是一个相当长的解决方案,我不知道我需要检查多少行滞后/领先。
这是数据示例:
Company Year Country Type
A 2018 US null
A 2018 US null
A 2019 US null
B 2018 AU Gold
B 2019 AU Black
B 2019 BR Gold
C 2019 FR Silver
C 2019 CA Silver
C 2019 DE Gold
预期输出:
Company Year Country Type
A 2018 US null
A 2018 US null
A 2019 US null
B 2018 AU Gold
B 2019 AU Gold
B 2019 BR Gold
C 2019 FR Gold
C 2019 CA Gold
C 2019 DE Gold
您可以使用count
分析函数
SELECT company,year,country,CASE
WHEN COUNT(
CASE WHEN type = 'Gold' THEN 1
END ) OVER(PARTITION BY company) > 0 THEN 'Gold'
ELSE type
END AS type
FROM t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.