按组列出的sql平均百分比

8fsztsew  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(326)

我有一些样本记录表1(将有100多条记录)

lastname    courtesy    
Lane          3  
Lane          4  
Lane          5  
Lane         12   
Santana       4  
Santana       5

我的查询是按姓氏获取平均百分比组,而不是按姓氏分组
你可以看到莱恩和桑塔纳还没有组队。
请更正查询。谢谢您。

SELECT
  lastname,
  courtesy,
  percentage = AVG(courtesy) * 100 / SUM(AVG(courtesy)) OVER (PARTITION BY lastname)
FROM echo
GROUP BY
  lastname, courtesy

结果

lastname    courtesy    percentage
Lane         3           12
Lane         4           16
Lane         5           20
Lane         12          50
Santana      4           44
Santana      5           55

结果是这样的

lastname    percentage
Lane         16        (4/24)
Satana       22        (2/9)
count (lastname) / sum (courtesy)  group by lastname
u5rb5r59

u5rb5r591#

我想这就是你想要的逻辑:

SELECT lastname,
       SUM(SUM(courtesy)) OVER (ORDER BY lastname),
       COUNT(*) * 1.0 / SUM(courtesy)
FROM echo
GROUP BY lastname;

相关问题