2011-05-26 57 views
0

方案1:集团通过与消除不同的价值

表:

id column1 column2 
1 "bla" "foo" 
2 "bla" "bar" 

我想按column1,并得到空为column2,导致有没有在所有行相同的值。

方案2:

表:

id column1 column2 
1 "bla" "foo" 
2 "bla" "foo" 

我想按column1并获得foocolumn2,造成column2所有的值相等。

是否有可能通过sql语句解决这个问题?

回答

2

既然你要组由column1,一个办法知道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个值,那么上面的查询就可以了,否则你需要下列之一的情况进行处理column2null

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的情况下,

+0

这应该比子选择或连接快许多。尼斯。 – 2011-05-26 17:41:13

+0

如果column2可以包含NULL,那么如果您有两行,一个是NULL,另一个是值,则不起作用。 – eaolson 2011-05-27 00:59:03

+0

@eaolson感谢您指出。我已经提出了一个新的查询 – 2011-05-27 06:07:50

0

试试这个:

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