获得每组独特结果的联合

时间:2014-06-24 10:56:58

标签: sql-server-2008 tsql dataset comparison

如果每个圆圈都显示一个结果集,那么如何将结果标记为红色(仅在单个集合中找到的值)作为单个集合而不必将每个集合与所有其他集合进行比较?

Sets

目前我正在将每个集合与其他集合进行比较

(SELECT ID FROM MyTable WHERE Value = 1
    EXCEPT
    (SELECT ID FROM MyTable WHERE Value = 2
    UNION
    SELECT ID FROM MyTable WHERE Value = 3))
UNION
(SELECT ID FROM MyTable WHERE Value = 2
    EXCEPT
    (SELECT ID FROM MyTable WHERE Value = 1
    UNION
    SELECT ID FROM MyTable WHERE Value = 3))
UNION
(SELECT ID FROM MyTable WHERE Value = 3
    EXCEPT
    (SELECT ID FROM MyTable WHERE Value = 1
    UNION
    SELECT ID FROM MyTable WHERE Value = 2))

1 个答案:

答案 0 :(得分:2)

假设只有1个ID和Value的组合。

SELECT ID
FROM MyTable
GROUP BY ID
HAVING COUNT(ID) = 1

由于ID和Value只能有1个组合,当您对ID进行分组并且计数大于1时,表示其他结果集中存在相同的ID,因此它不会显示为条件是有COUNT(ID)= 1 。 如果您的值不是1,2和3,则应将条件设为

WHERE Value IN (1,2,3)

在上面的查询中。