既然你要組由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
個值,那麼上面的查詢就可以了,否則你需要下列之一的情況進行處理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
的情況下,
這應該比子選擇或連接快許多。尼斯。 – 2011-05-26 17:41:13
如果column2可以包含NULL,那麼如果您有兩行,一個是NULL,另一個是值,則不起作用。 – eaolson 2011-05-27 00:59:03
@eaolson感謝您指出。我已經提出了一個新的查詢 – 2011-05-27 06:07:50