根据窗口功能的结果应用分组依据

时间:2018-11-09 04:51:55

标签: mysql

我使用窗口函数来计算每种产品的利润百分比

SELECT 
    productCode, productProfit, paymentDate, productName,
    productProfit/sum(productProfit)  OVER (PARTITION BY productCode) AS percent
FROM
    profit;

输出 enter image description here

下一步,我要计算AVG(百分比)。我如何将其纳入第一条陈述?

结果将如下所示 enter image description here

1 个答案:

答案 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