获取分组值除以总计

时间:2016-02-22 14:45:22

标签: postgresql group-by resultset

我有一张这样的表:

+----+---------------+----------+
| id | city          | price    |
+----±---------------±----------+
| 1  | Paris         | 2.000,00 |
| 2  | London        | 500,00   |
| 3  | Paris         | 500,00   |
| 4  | Madrid        | 1.000,00 |
±----±---------------±----------±

这样的请求:

select
    city,
    sum(price)
from orders
group by city
order by sum(price) desc

这给我一个结果:

+----------+---------------+
| city     | SUM(price)    |
+----------±---------------±
| Paris    | 2.500,00      |
| Madrid   | 1.000,00      |
| London   | 500,00        |
±----------±---------------±

我想要的是第三列中每个城市的价格比率,因此巴黎将有62.50%,依此类推:

+----------+---------------+-------------+
| city     | SUM(price)    | Ratio       |
+----------±---------------±-------------+
| Paris    | 2.500,00      | 62,50       |
| Madrid   | 1.000,00      | 25          |
| London   | 500,00        | 12,50       |
±----------±---------------±-------------±

目前,我必须在获取第一个结果集后计算PHP中的最后一列。我想知道是否有任何方法可以直接在SQL中执行此操作?

2 个答案:

答案 0 :(得分:2)

我建议使用CTE来改善阅读,但你会得到与Giorgios回答相同的表现。

WITH cte0 as (
     SELECT *
     FROM Orders
     WHERE <filters>
),
cte as (
     SELECT SUM(price) total
     FROM cte0 
)
SELECT city, sum(price), 100.0 * SUM(Price) /  cte.total
FROM cte0 
CROSS JOIN cte
GROUP BY city

答案 1 :(得分:1)

您可以使用子查询来获取总价:

select
    city,
    sum(price),
    100.0 * sum(price) / (select sum(price) from Orders) AS Ratio
from Orders
group by city
order by sum(price) desc

Demo here

或者,您可以使用CROSS JOIN

select
    city,
    sum(price),
    100.0 * sum(price) / t.total_price AS Ratio
from Orders
cross join (select sum(price) as total_price from Orders) AS t
group by city
order by sum(price) desc