2012-10-16 22 views
0

我有一個數據庫表包含兩個成本。我想找到這兩列的不同成本。我也想找到這些成本出現的次數。該表可能看起來像計數和在多列不同

|id|cost1|cost2| 
|1 |50 |60 | 
|2 |20 |50 | 
|3 |50 |70 | 
|4 |20 |30 | 
|5 |50 |60 | 

在這種情況下,我想結果是兩列在不同的和計數的出現次數。所以,我想結果是

|distinctCost|count| 
|20   |2 | 
|30   |1 | 
|50   |4 | 
|60   |2 | 
|70   |1 | 

和理想的有序

|disctinCost1|count| 
|50   |4 | 
|60   |2 | 
|20   |2 | 
|70   |1 | 
|30   |1 | 

我可以做這樣的事情

select DISTINCT c FROM (SELECT cost1 AS c FROM my_costs UNION SELECT cost2 AS c FROM my_costs); 

得到明顯超過兩列,我可以得到的數每列做

select cost1, count(*) 
from my_costs 
group by cost1 
order by count(*) desc; 

我的問題是如何獲得兩列的計數?我被困在如何計算每個單獨的列,然後將其添加。

任何指針,將不勝感激。

我正在使用Oracle DB。

感謝

回答

2

通過結合你的兩個查詢..

select cost, count(*) 
from 
(
    SELECT id, cost1 AS cost FROM my_costs 
    UNION ALL 
    SELECT id, cost2 AS c FROM my_costs 
) v 
group by cost 
order by count(*) desc; 

(如果當行有COST1和cost2平等的,要算一次,如果不是兩次,改變union allunion

0

可以使用逆透視聲明:

select * 
from 
(
    SELECT cost , count(*) as num_of_costs 
    FROM my_costs 
    UNPIVOT 
    (
    cost       
    FOR cost_num IN (cost1,cost2) 
) 
group by cost 
) 
order by num_of_costs desc;