简体   繁体   中英

SQL: count occurrences of values

Let

user | fruit
------------
1    | apple
1    | apple
1    | apple
2    | apple
2    | apple
1    | pear

Trying to combine count and group by to get

user | apples | pears
---------------------
1    | 3      | 1
2    | 2      | 0

Any hints on how to proceed are appreciated.

Use case expressions to do conditional counting:

select user,
       count(case when fruit = 'apple' then 1 end) as apples,
       count(case when fruit = 'pear' then 1 end) as pears
from tablename
group by user

If you´re working on an Oracle, you would use the PIVOT-function:

SELECT *
  FROM fruit t
 PIVOT (COUNT(fruit) AS cnt 
          FOR(fruit) IN ('apple' AS apple
                       , 'pear' AS pear) );

More details and full samples on PIVOT / UNPIVOT you´ll find in the web (fe here https://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM