2017-11-11 65 views
1

嗨我有這張表,並且只想查詢所有行共同的條目(日誌Id)。
只選擇所有行共同的條目

Log Id Person Id Main(Y/N) Sex Rel  
    01   21 Y   M  ATH  
    02   21 Y   M  ATH  
    03   21 Y   F  ATH  
    04   21 Y   M  ATH  
    05   21 Y   F  ATH  

預期的結果會是這樣:

PersonId Y/N Sex Rel  
    21 Y  - ATH  

你看,我想只能說明什麼是共同的所有行,否則無效。這只是一個非常複雜的查詢的一部分。以下是一個大問題。

Log Id Person Id Main(Y/N) Sex Rel  
    01   21 Y   M  ATH  
    02   21 Y   M  ATH  
    03   21 Y   F  ATH  
    04   21 Y   M  ATH  
    05   21 Y   F  ATH  
    01   22 N   M  ATH  
    02   22 N   M  ATH  
    03   22 N   M  ATH  
    04   22 N   M  ATH  
    05   22 N   M  ATH  

預期的結果會是這樣:

PerId Y/N S Rel  
    21 Y - ATH  
    22 N M ATH  
+0

你有'Y'和'N'爲'22'。那爲什麼結果應該包含'N'爲'22'? –

回答

1

以下查詢應該工作:

select personId, 
     (case when count(distinct main)>1 then '' else main end) as Main, 
     (case when count(distinct sex) >1 then '' else sex end) as Sex, 
     (case when count(distinct religion)>1 then '' else religion end) as Religion 
from yourTableName 
group by personId; 

結果:

personId | Main | Sex | Religion 
    21  | Y |  | ATH 
    22  | N | M | ATH 

Click here for DEMO

Oracle解決方案:(如建議通過@MarmiteBomber)

select personId, 
     (case when count(distinct main)=1 then max(main) else ' ' end) as Main, 
     (case when count(distinct sex)=1 then max(sex) else ' ' end) as Sex, 
     (case when count(distinct religion)=1 then max(religion) else ' ' end) as Religion 
from t 
group by personId; 

DEMO in Oracle

希望它能幫助!

+0

我得到的不是GROUP BY表達式而不是personId的列 –

+0

您確定您使用的是MySQL嗎? –

+1

@TribensonAzupardo對於'Oracle',您還必須使用聚合函數(例如'MAX'或'MIN')來包含列。例如。 '當計數(不同主)> 1然後NULL其他最大(主)結束'的情況下 –

0

我會寫爲:

select personId, 
     (case when min(main) = max(main) then max(main) end) as Main, 
     (case when min(sex) = max(sex) then max(sex) end) as Sex, 
     (case when min(religion) = max(religion) then max(religion) end) as Religion 
from yourTableName 
group by personId; 

注:本使用NULL未知值。我認爲這更符合SQL。如果你真的想要連字符,你可以使用else '-'

爲什麼用min()max()而不是count(distinct)?原因很簡單:性能。 count(distinct)比其他聚合操作更昂貴(因爲中間結果必須存儲所有可能值的列表)。

+0

感謝您的信息。但我有一個問題:假設有10-15個宗教的許多人。在這種情況下,min()和max()是否比count()便宜? –

+1

@Harshil。 。 。 'min()'和'max()'快於*'count(distinct)'*。問題是「明顯」。是的,特別是當有更多行時,情況確實如此。 –

相關問題