首页 > 解决方案 > SQL - 选择子句中的子选择 - 如何创建决定唯一性逻辑的列

问题描述

我正在尝试编写子选择,它将遍历返回的数据,然后检查所有状态,然后决定唯一性逻辑。

有没有办法找出以下?

我试图这样写,但我需要在一个案例陈述中使用它

SELECT a.id, a.status,
,(SELECT 
    CASE WHEN b.STATUS = 'Active' THEN 1 ELSE 0 END
    CASE WHEN b.STATUS = 'Expired' THEN 1 ELSE 0 END 
    FROM b.TABLE
    WHERE a.id=b.id )AS unique
FROM my.TABLE 

结果应该看起来像https://i.stack.imgur.com/qCA74.png过期案例的图片

提前感谢您的任何提示。

标签: sqlsubquerysql-subselect

解决方案


使用窗口函数:

select t.*,
       (case when row_number() over (partition by id
                                     order by case status when 'Active' then 1 when 'Expired' then 2 else 3 end
                                    ) = 1
             then 1 else 0
        end) as unique_flag
from my.table t;

推荐阅读