繁体   English   中英

来自多行的SQL检查ID值

[英]SQL check id value from multiple rows

我想根据特定条件计算ID的数量。

我有一个包含3列的表:id(不是唯一的),foo(整数)和bar(字符串)。

    id| foo | bar   
     1|  0  | yes    
     1|  1  | no
     1|  1  | no    
     2|  0  | no  
     2|  1  | no    
     3|  0  | yes
     3|  1  | no
     3|  2  | yes
     4|  0  | yes  

我希望查询给我一个ID列表。 条件:

a. id should have more than 1 entry.  
b. id needs to have foo = 0 AND bar = yes.  
c. if (b) is satisfied, it also needs to have all the rest of foo to have bar = no. (the number of foo for each id is unknown)

在上面的示例中,查询应返回id =1。(Id = 2无效,因为当foo = 0时bar =否,Id = 3无效,因为当foo = 2时bar = yes。)

你可以得到的名单id使用S group byhaving 您的条件的确切翻译是:

select id
from t
group by id
having count(*) > 1 and
       sum( foo = 0 and bar = 'yes' ) = 1 and
       sum( bar = 'no' ) = count(*) - 1;

如果需要计数而不是列表,则可以使用子查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM