╔════╦══════╦════════════╗
║ ID ║ NAME ║ WORK ║
╠════╬══════╬════════════╣
║ 1 ║ a ║ complete ║
║ 1 ║ a ║ complete ║
║ 2 ║ b ║ incomplete ║
║ 3 ║ c ║ complete ║
║ 4 ║ d ║ incomplete ║
║ 4 ║ d ║ complete ║
║ 5 ║ e ║ complete ║
║ 5 ║ e ║ complete ║
║ 5 ║ e ║ incomplete ║
║ 6 ║ f ║ incomplete ║
║ 6 ║ f ║ incomplete ║
╚════╩══════╩════════════╝
我想构建一个查询,该查询只检索所有作业完成或单个不完整的ID
例如在上面的数据中,我想只得到这些id
1, 2, 3, 4, 5
不是6因为它有多个不完整的作品
答案 0 :(得分:5)
SELECT ID, Name
FROM tableName
GROUP BY ID, NAME
HAVING SUM(CASE WHEN Work = 'Incomplete' THEN 1 ELSE 0 END) < 2
答案 1 :(得分:1)
您应该可以使用NOT EXISTS
执行此类操作:
SELECT DISTINCT H.ID
FROM Homework H
WHERE H.Work = 'Complete'
AND NOT EXISTS (
SELECT *
FROM Homework H2
WHERE H2.Work != 'Complete' AND H2.ID = H.ID )
这是SQL Fiddle。
编辑 - 实际上,只是注意到你也想要那些只有一个不完整的东西 - 让我编辑。应该这样做:
SELECT DISTINCT H.ID
FROM Homework H
GROUP BY H.ID
HAVING COUNT(*) = 1 OR (
NOT EXISTS (
SELECT *
FROM Homework H2
WHERE H2.Work != 'Complete'
AND H2.ID = H.ID ))
祝你好运。