2011-05-26 53 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