如果我们有一个像这样的表:
col1 | col2
-----------
A | 1
B | 2
A | 1
C | 16
B | 3
如何确定col1中给定值的所有行是否相同? 例如,这里只有'1代表A,但对于B,我们有'2'和'3'。 类似的东西:
A | true
B | false
C | true
答案 0 :(得分:3)
select col1, case when count(distinct col2) = 1
then 'true'
else 'false'
end as same_col2_results
from your_table
group by col1
答案 1 :(得分:2)
出于此目的,我倾向于使用min()
和max()
,而不是count(distinct)
:
select col1,
(case when min(col2) = max(col2) then 'true' else 'false' end) as IsCol2Same
from table t
group by col1;
然后是NULL
值的问题。如果你想忽略它们(所以一列实际上可以有两个值,NULL
和另一个值),那么上面就好了(就像count(distinct)
)。如果您想以与其他值相同的方式处理NULL
,那么您需要一些额外的测试:
select col1,
(case when min(col2) is null then 'true' -- All NULL
when count(col2) <> count(*) then 'false' -- Some NULL
when min(col2) = max(col2) then 'true' -- No NULLs and values the same
else 'false'
end) as IsCol2Same
from table t
group by col1;
答案 2 :(得分:0)
Select distinct(t1.col1), case when t1.col2=t2.col2 then TRUE else FALSE end
from table t1, table t2 where t1.col1=t2.col2