我有一张包含以下内容的表:
Fruit_id Fruit1 Fruit2
-------------------------------------
1 Apple Orange
2 Orange Orange
3 Orange Orange
4 Banana Banana
5 Apple Orange
我想计算每个水果的总数,以便输出类似
Fruit Frequency
---------------------------
Apple 2
Banana 2
Orange 6
我试过了
select distinct Fruit1, count(Fruit1 Fruit2) from Fruits group by Fruit1 order by count(Fruit1 Fruit2);
我也尝试过:
select distinct Fruit1, count(Fruit1 || Fruit2) from Fruits group by Fruit1 order by count(Fruit1 Fruit2);
我是oracle sql的新手所以请理解我的无知
答案 0 :(得分:1)
您可以使用以下内容:
select fruits, count(*) as freq
from (select fruit1 as fruits
from tbl
union all
select fruit2 as fruits
from tbl)
group by fruits
答案 1 :(得分:1)
您可以获取Fruit1和Fruit2列中每个不同水果值的计数,然后将这些值与SUM聚合一起添加。
“技巧”是使用内联视图将两个结果与UNION ALL集合运算符连接起来。
SELECT f.fruit, SUM(f.cnt) AS cnt
FROM ( SELECT d.Fruit1 AS fruit, COUNT(1) AS cnt FROM Fruits d GROUP BY d.Fruit1
UNION ALL
SELECT e.Fruit2 AS fruit, COUNT(1) AS cnt FROM Fruits e GROUP BY e.Fruit2
) f
GROUP BY f.fruit
ORDER BY f.fruit