id color
1 Yellow
1 Pink
2 Yellow
2 blue
3 Yellow
3 Yellow
4 Red
只希望所有行的颜色都相同的ID。
尝试了多种方法,但没有得到任何答案。
;WITH CTE AS (
select ROW_NUMBER() OVER(PARTITION BY A.ID,A.COLOR ORDER BY A.ID,A.COLOR)RNO,A.ID,A.COLOR from COLOR a join COLOR b on a.id = b.id and a.color=b.color
)
SELECT DISTINCT ID, COLOR FROM CTE --WHERE RNO > 1
SELECT *
FROM color a join (
SELECT id, color, count(*) as qty
FROM color
GROUP BY id, color
HAVING COUNT(*) > 1
) b on a.id = b.id and a.color = b.color
select * from (
Select color,id,count(1)cnt from COLOR
group by color,id
having count(1) = 1
union all
Select color,id,count(1)cnt from COLOR
group by color,id
having count(1) > 1
) as t where cnt between 1 and 4
答案 0 :(得分:2)
GROUP BY
和HAVING
将完成此工作。 COUNT(DISTINCT color)
将在每个组中返回不同的颜色,如果返回1,则该组中的所有行都有一种颜色。
select id from my_table
group by id
having count(distinct color) = 1
答案 1 :(得分:0)
您可以使用not exists
:
select c.*
from color c
where not exists (select 1 from color c1 where c1.id = c.id and c1.color <> c.color);