Postgres - AVG计算
Postgres - AVG calculation
请参考以下查询
SELECT sum(sales) AS "Sales",
sum(discount) AS "discount",
year
FROM Sales_tbl
WHERE Group by year
现在我还想显示一个 AVG(sales) 列,该列具有相同的值并且基于总销售额列
输出
请指教
将AVG()
用作window函数:
WITH t AS (
SELECT
SUM(sales) AS sales, SUM(discount) AS discount, year
FROM tbl_sales
GROUP BY year
)
SELECT *,AVG(sales) OVER w_total
FROM t
WINDOW w_total AS (RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY year;
框架 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
在这种情况下几乎是可选的,但在 window 函数中尽可能明确被认为是一种很好的做法。所以你也可以这样写查询:
WITH t AS (
SELECT
SUM(sales) AS sales, SUM(discount) AS discount, year
FROM tbl_sales
GROUP BY year
)
SELECT *,AVG(sales) OVER ()
FROM t
ORDER BY year;
演示:db<>fiddle
请参考以下查询
SELECT sum(sales) AS "Sales",
sum(discount) AS "discount",
year
FROM Sales_tbl
WHERE Group by year
现在我还想显示一个 AVG(sales) 列,该列具有相同的值并且基于总销售额列
输出
请指教
将AVG()
用作window函数:
WITH t AS (
SELECT
SUM(sales) AS sales, SUM(discount) AS discount, year
FROM tbl_sales
GROUP BY year
)
SELECT *,AVG(sales) OVER w_total
FROM t
WINDOW w_total AS (RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY year;
框架 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
在这种情况下几乎是可选的,但在 window 函数中尽可能明确被认为是一种很好的做法。所以你也可以这样写查询:
WITH t AS (
SELECT
SUM(sales) AS sales, SUM(discount) AS discount, year
FROM tbl_sales
GROUP BY year
)
SELECT *,AVG(sales) OVER ()
FROM t
ORDER BY year;
演示:db<>fiddle