sql - 如何检查非唯一键是否包含特定值对?
问题描述
我有下表:
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
解决方案
如果您想要具有 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
推荐阅读
- python - 当我在 python3 中使用 readline 函数时,无法将变量存储到新变量中
- mongodb - 我无法通过使用纬度和经度来获取记录,使用 Mongodb
- c# - 使用 OpenCV 连续捕获桌面循环
- nuget - TeamCity 在应该发布 4 时仅将 1 个包发布到 NuGet 提要
- c# - 如何让安装程序注册一个 IE 插件
- teamcity - 停止 TeamCity 从更新命令行的程序中捕获许多日志行
- c# - 是否有使用国家/地区名称从 UTC 时间转换为本地时间的功能?
- excel-formula - Excel #REF!将工作公式应用于外部文件时出错
- c++ - 使用 Qt 5.11 和 Crypto++ 在 QtCreator 中检测到“RuntimeLibrary”不匹配
- java - 我无法使用 for 循环访问数组的索引,但我可以手动完成