![](/img/trans.png)
[英]Group records by UserID, select where on one column value and sum another
[英]SQL count a value for each userID record except where one record value of userId is x
我被困住了,我现在知道如何提出我的问题,所以我用想要的结果创建了一个假设的情景。
我正在尝试创建一个查询,该查询对每个用户ID除记录有水果是香蕉的用户ID以外的水果数量进行计数。
+----------+--------+--------------+
| recordID | userId | Fruit |
+----------+--------+--------------+
| 0 | 112 | Apple |
| 1 | 112 | Banana |
| 2 | 112 | kiwi |
| - | - | - |
| 3 | 113 | Banana |
| 4 | 113 | Pear |
| - | - | - |
| 5 | 114 | Dragon fruit |
| 6 | 114 | Pineapple |
| - | - | - |
| 7 | 115 | Dragon Fruit |
| 8 | 115 | Cherry |
+----------+--------+--------------+
想要的结果:
+-------+-------------+--+
| count | fruit | |
+-------+-------------+--+
| 2 | dragonfruit | |
| 1 | pineapple | |
| 1 | cherry | |
+-------+-------------+--+
忽略用户ID为113的用户,因为该用户具有水果和香蕉值的记录。
您只需要一个过滤子句:
select fruit, count(*)
from t
where not exists (select 1
from t t2
where t2.userid = t.userid and t2.fruit = 'banana'
)
group by fruit
order by count(*) desc;
使用not in
和子查询
select count(*),fruit from
(
select * from t where userid not in(
select userId from t where Fruit='Banana'
)
) t1 group by fruit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.