选择语句以在没有值的情况下组合组

时间:2016-11-16 22:14:38

标签: sql oracle

我有一张表XXX

X    Y
---- -----------
A    1
A    2
A    3
B    1
B    2
C    1
C    2
C    3

我正在尝试从列X中找到值Y中没有值3的不同值

如果是样本数据,我应该收到一个值:

B

3 个答案:

答案 0 :(得分:4)

您可以使用COUNTHAVING

SELECT X
FROM XXX
GROUP BY X
HAVING COUNT(CASE WHEN Y = 3 THEN 1 END) = 0

ONLINE DEMO

答案 1 :(得分:1)

您可以使用not in和subselect

 select distinct x from XXX 
 where  x not  in (
              select x from XXX
              where  Y=3 ) 

答案 2 :(得分:0)

从整套开始。

减去你不想要的部分。

WITH
BASE AS
(
    SELECT 'A' x,    1 y FROM DUAL UNION ALL
    SELECT 'A' x,    2 y FROM DUAL UNION ALL
    SELECT 'A' x,    3 y FROM DUAL UNION ALL
    SELECT 'B' x,    1 y FROM DUAL UNION ALL
    SELECT 'B' x,    2 y FROM DUAL UNION ALL
    SELECT 'C' x,    1 y FROM DUAL UNION ALL
    SELECT 'C' x,    2 y FROM DUAL UNION ALL
    SELECT 'C' x,    3 y FROM DUAL
)

SELECT DISTINCT X
FROM BASE

MINUS

SELECT X
FROM BASE
WHERE Y = 3
;