我想基于某个条件来计算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 = no.Id = 3因为bar而无效 =当foo = 2时是。)
答案 0 :(得分:0)
您可以使用id
和group by
获取having
的列表。您的条件的确切翻译是:
select id
from t
group by id
having count(*) > 1 and
sum( foo = 0 and bar = 'yes' ) = 1 and
sum( bar = 'no' ) = count(*) - 1;
如果您想要计数而不是列表,则可以使用子查询。