首页 > 解决方案 > 如何检查非唯一键是否包含特定值对?

问题描述

我有下表:

CREATE TABLE TABLE1 (
    ID,
    status,
    timestamp
)

我想检查状态为 A 的 ID,也检查状态为 B 和状态 C 的 ID。我希望将它们按如下方式计算:

SELECT 
ID
,SUM(CASE WHEN status = 'A' then 1 
WHEN 
-- something like the following:
status = 'B'  and (status = 'C' AND [timestamp of C] > [timestamp of B]) then 1
else 0 END) as SUCCESS
    FROM TABLE1
    GROUP BY ID

我需要self join这里吗?如何获得具有此状态 = B & C 且 timestampB < timestampC 条件的 ID?

示例表:

INSERT INTO TABLE1(ID, status, timestamp)
VALUES(1, A, 5)
VALUES(2,B, 3)
VALUES(2, D, 5)
VALUES(3, A, 5)
VALUES(4, B, 9)
VALUES(4,C,10)  

结果应该是:

1, 1
2, 0
3, 1
4, 1

标签: sql

解决方案


如果您想要具有 A 且 B 的时间戳小于 C 的 id,请使用:

select id
from t
group by id
having sum(case when status = 'A' then 1 else 0 end) > 0 and
       min(case when status = 'B' then timestamp end) < max(case when status = 'C' then timestamp end)

编辑:

select id,
       (case when sum(case when status = 'A' then 1 else 0 end) > 0 and
                  min(case when status = 'B' then timestamp end) < max(case when status = 'C' then timestamp end)
             then 1 else 0
        end) as success_flag
from t
group by id

推荐阅读