1
╔════╦══════╦════════════╗
║ 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,因为它有不止一个不完整的工作

4

2 回答 2

5
SELECT  ID, Name
FROM    tableName
GROUP   BY ID, NAME
HAVING  SUM(CASE WHEN Work = 'Incomplete' THEN 1 ELSE 0 END) < 2
于 2013-02-03T05:41:37.770 回答
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 小提琴

编辑——实际上,刚刚注意到你还想要那些不完整的——让我编辑。那应该这样做:

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 ))

还有更多小提琴:http ://sqlfiddle.com/#!3/c7d43e/3

祝你好运。

于 2013-02-03T05:38:39.413 回答