获取分组值除以总数

Nug*_*get 5 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 |
±----±---------------±----------±
Run Code Online (Sandbox Code Playgroud)

和这样的请求:

select
    city,
    sum(price)
from orders
group by city
order by sum(price) desc
Run Code Online (Sandbox Code Playgroud)

这给了我一个结果:

+----------+---------------+
| city     | SUM(price)    |
+----------±---------------±
| Paris    | 2.500,00      |
| Madrid   | 1.000,00      |
| London   | 500,00        |
±----------±---------------±
Run Code Online (Sandbox Code Playgroud)

我想要的是第三列中每个城市的价格比率,这样巴黎就有 62.50% 等等,如下所示:

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

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

Jua*_*eza 6

我建议使用 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
Run Code Online (Sandbox Code Playgroud)