我有一个包含两个成本的数据库表。我想找到这两列的明显成本。我还想找到这些费用出现的计数。该表可能看起来像
|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。
由于
答案 0 :(得分: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 all
更改为union
)
答案 1 :(得分:0)
您可以使用unpivot语句:
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;