簡體   English   中英

SQL為每個userID記錄計數一個值,除非userId的一個記錄值是x

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM