SQL选择不同的COL1,其中COL2是_而COL2是从不_?

时间:2017-08-10 01:26:02

标签: sql distinct

(使用Oracle SQLDeveloper) 我需要生成一个SQL语句,它将找到形状为正方形而不是圆形的不同颜色数。

下表标题为:MYOBJECTS

目前我的SQL语句(不完整)是:

SELECT DISTINCT COLOR, SHAPE FROM MYOBJECTS WHERE ((SHAPE = 'square') AND (..........)); 

enter image description here

仅供参考,答案应该是:

颜色 |的 SHAPE
黄色|方
棕色|方

任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

嗯。嗯。 。 。一种方法是两级聚合。另一个会使用子查询:

SELECT COUNT(DISTINCT COLOR)
FROM MYOBJECTS o
WHERE SHAPE = 'square' AND
      NOT EXISTS (SELECT 1
                  FROM MYOBJECTS o2
                  WHERE o2.color = o.color AND o2.SHAPE = 'circle'
                 );

编辑:

哦,我注意到你想要的是各行,而不是计数:

SELECT DISTINCT COLOR, SHAPE
FROM MYOBJECTS o
WHERE SHAPE = 'square' AND
      NOT EXISTS (SELECT 1
                  FROM MYOBJECTS o2
                  WHERE o2.color = o.color AND o2.SHAPE = 'circle'
                 );

答案 1 :(得分:1)

另一个group by答案是不正确的,但需要进行心理练习才能通过分组来完成...

SELECT color FROM MYOBJECTS GROUP BY color HAVING SUM(shape = 'square') > 0 AND SUM(shape = 'circle') = 0

答案 2 :(得分:0)

我认为你只需要GROUP BY

SELECT COLOR, SHAPE
FROM MYOBJECTS
WHERE SHAPE = 'square'
GROUP BY COLOR