查看同一组中的所有记录是否为可接受的类型

时间:2016-05-16 13:01:17

标签: sql sql-server

考虑下表。每个文档(id)属于一个组(group_id)。

-----------------------
id    group_id    value
-----------------------
 1       1         A
 2       1         B
 3       1         D
 4       2         A
 5       2         B
 6       3         C
 7       4         A
 8       4         B
 9       4         B
10       4         B
11       4         C
12       5         A
13       5         A
14       5         A
15       6         B
16       6         NULL
17       6         NULL
18       6         D
19       7         NULL
20       8         B

1 /每个文档的值为NULLABCD

2 /如果同一组中的文档都有AB作为值,则该组已完成

3 /在这种情况下,所需的输出将为:

---------------------
group_id    completed
---------------------
   1          0       <== because document 3 = D
   2          1       <== all documents have either A or B as a value
   3          0       <== only one document in the group, value C
   4          1       <== all documents have either A or B as a value
   5          1       <== all documents have value A
   6          0       <== because of NULL values and value D
   7          0       <== NULL
   8          1       <== only one document, value B

是否可以查询此结果集?

由于我对SQL不是很有经验,所以我们将不胜感激!

1 个答案:

答案 0 :(得分:7)

试试这个

SELECT [group_id], 
       CASE 
         WHEN Count(CASE WHEN [value] IN ( 'A', 'B' ) THEN 1 END) = Count(*) THEN 1 
         ELSE 0 
       END AS COMPLETED 
FROM   yourtable 
GROUP  BY [group_id]