【问题标题】:SQL count a value for each userID record except where one record value of userId is xSQL 为每个 userID 记录计数一个值,除非 userId 的一个记录值为 x
【发布时间】:2018-09-28 11:06:56
【问题描述】:

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

我正在尝试创建一个查询,该查询计算每个用户 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 的用户,因为它有一个值为 Banana 的水果记录。

【问题讨论】:

    标签: mysql sql group-by subquery


    【解决方案1】:

    你只需要一个过滤子句:

    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;
    

    【讨论】:

      【解决方案2】:

      使用not in 和子查询

      select count(*),fruit from
      (
      select * from t where userid not in(
      
      select userId from t where Fruit='Banana'
      )
      ) t1 group by fruit
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-02
        • 2021-01-26
        • 1970-01-01
        相关资源
        最近更新 更多