2017-11-11 63 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)'*。问题是“明显”。是的,特别是当有更多行时,情况确实如此。 –

相关问题