如何编写PostgreSQL查询以获取具有相同值的记录的总和组

hsgswve4  于 2022-11-04  发布在  PostgreSQL
关注(0)|答案(2)|浏览(168)

假设我有下面的表

id | items   |  price  |
  1| item_1  |  15.0   |
  2| item_2  |  10.0   |
  3| item_1  |  15.0   |
  4| item_1  |  15.0   |
  5| item_2  |  10.0   |
  6| item_2  |  10.0   |
  7| item_3  |  25.0   |

我需要以下输出

items   |  price  | count | sum  |
 item_1  |  15.0   | 3     | 45.0 |
 item_2  |  10.0   | 3     | 30.9 |
 item_3  |  25.0   | 1     | 25.0 |
fwzugrvs

fwzugrvs1#

您必须执行如下查询,

select items, price, count(items) as count, sum (price) as sum from table1 group by items, price
nle07wnf

nle07wnf2#

我们可以在这里使用解析函数:

WITH cte AS (
    SELECT *, SUM(price) OVER (PARTITION BY items, price) sum,
              COUNT(*) OVER (PARTITION BY items, price) count
    FROM yourTable
)

SELECT DISTINCT items, price, count, sum
FROM cte
ORDER BY items;

相关问题