分组依据并消除变化的值

问题描述

| 方案1: 表:
id column1 column2
1  \"bla\"   \"foo\"
2  \"bla\"   \"bar\"
@H_502_2@

我想按
column1@H_502_2@分组,而对ѭ2get取空,因为所有行中的值都不相同。

方案2:

表:

id column1 column2
1  \"bla\"   \"foo\"
2  \"bla\"   \"foo\"
@H_502_2@

我想对
column1@H_502_2@进行分组,并将
column2@H_502_2@得到
foo@H_502_2@,因为
column2@H_502_2@的所有值都相等。

是否可以通过sql语句解决此问题?
    


解决方法

由于您要按ѭ1进行分组,因此知道
column2
是否具有相同值的一种方法是检查
max(column2) = min(column2)
,因此这应该可行:
select column1,case 
                    when max(column2) = min(column2) then max(column2)
                    else null
                end as col2
  from tabletest
 group by column1;
编辑 如果您的
column2
无法接受
null
值,那么上面的查询就可以了,否则,当
column2
null
时,您需要使用以下查询:
select t.column1,case 
                      when (select max(1) from tabletest where column2 is null and column1 = t.column1) = 1 then null
                      when max(t.column2) = min(t.column2) then max(t.column2)
                      else null
                  end as col2
  from tabletest t
 group by t.column1;
唯一的区别是我们需要添加一个
case
条件来覆盖
column2 is null
时的情况     ,尝试这个:
select id = t.id,col1 = t.col1,col2 = case when t1.N < 2 then t.col2 end
from myTable t
join ( select col1,N=count(distinct col2)
       from myTable
       group by col1
     ) t1 on t1.col1 = t.col1