我使用窗口函数来计算每种产品的利润百分比
SELECT
productCode, productProfit, paymentDate, productName,
productProfit/sum(productProfit) OVER (PARTITION BY productCode) AS percent
FROM
profit;
下一步,我要计算AVG(百分比)。我如何将其纳入第一条陈述?
答案 0 :(得分:2)
您计算percent
的方法有点奇怪。看来您正在确定特定交易对整体利润的贡献。
无论如何,您可以简单地将现有查询的结果集用作Derived Table,并使用Year()
函数进行Group By
来计算Avg()
:>
SELECT
YEAR(dt.paymentDate) AS payment_date_year,
AVG(dt.percent) AS average_profit_percent
FROM
(
SELECT
productCode,
productProfit,
paymentDate,
productName,
productProfit/sum(productProfit) OVER (PARTITION BY productCode) AS percent
FROM
profit
) AS dt
GROUP BY
payment_date_year