Let
user | fruit
------------
1 | apple
1 | apple
1 | apple
2 | apple
2 | apple
1 | pear
尝试将
count
和group by
结合起来,以获取user | apples | pears
---------------------
1 | 3 | 1
2 | 2 | 0
希望能够得到关于如何进行的任何提示。
Let
user | fruit
------------
1 | apple
1 | apple
1 | apple
2 | apple
2 | apple
1 | pear
count
和group by
结合起来,以获取user | apples | pears
---------------------
1 | 3 | 1
2 | 2 | 0
希望能够得到关于如何进行的任何提示。
使用case
表达式进行条件计数:
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
SELECT *
FROM fruit t
PIVOT (COUNT(fruit) AS cnt
FOR(fruit) IN ('apple' AS apple
, 'pear' AS pear) );
您可以在网上找到有关PIVOT / UNPIVOT的更多详细信息和完整示例(例如这里https://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1)。