首页 > 解决方案 > SQL 根据 CASE 语句选择行

问题描述

如果存在,我想获得每个 ID 的“好”值,如果不存在,则获得“坏”值。

如果一个 ID 的 index='good',想要返回该 ID 的行。
如果一个 ID 只有 index='bad',想要得到那个。

你会怎么做?

在此处输入图像描述

标签: sqlapache-spark-sql

解决方案


你可以试试下面的 -

with cte as
(
select id, index, value, row_number() over(partition by id order by case when index='good' then 1 else 2 end) as rn
from tablename
)

select id,index, value
from cte where rn=1

推荐阅读