SQL为每个userID记录计数一个值,除非userId的一个记录值是x

时间:2018-09-28 11:06:56

标签: mysql sql group-by subquery

我被困住了,现在我知道如何提出问题了,所以我用想要的结果创建了一个假设的情景。

我正在尝试创建一个查询,该查询对每个用户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的用户,因为该用户具有记录的水果和香蕉值。

2 个答案:

答案 0 :(得分:2)

您只需要一个过滤子句:

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;

答案 1 :(得分:0)

使用not in和子查询

select count(*),fruit from
(
select * from t where userid not in(

select userId from t where Fruit='Banana'
)
) t1 group by fruit