2014-05-12 126 views
0

我必須包含以下表格:計數的Oracle SQL

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所以請理解我的無知

回答

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 
+0

作品!非常感謝。 – user3619807

1

您可以使用下列內容:

select fruits, count(*) as freq 
    from (select fruit1 as fruits 
      from tbl 
     union all 
     select fruit2 as fruits 
      from tbl) 
group by fruits 
+0

感謝您的快速響應。我會試一試 – user3619807

+0

我得到一個ORA-00936:缺少表達式錯誤 – user3619807

+0

@ user3619807查詢沒有錯,請參閱http://sqlfiddle.com/#!4/32c5c/1/0 。您可能錯誤地輸入了某些內容。你接受的答案實際上和我的相同,稍後公佈。 –