提问人:justnewbie89 提问时间:9/25/2019 更新时间:3/7/2021 访问量:3161
从另一列 sql / presto 计算百分比
Percentage calculation from another column sql / presto
问:
我有这张表
month_year shopid payment_method count
Jul-19 3lokpn99 CC 115
Jul-19 3lokpn99 PAYPALL 1
Jul-19 6jyhikmm CC 180
Jul-19 6jyhikmm PAYPALL 7
Aug-19 3lokpn99 CC 108
Aug-19 3lokpn99 PAYPALL 4
Aug-19 6jyhikmm CC 114
Aug-19 6jyhikmm PAYPALL 3
我正在寻找的是计算该月每种付款方式的百分比。 期望的结果是这样的
month_year shopid payment_method count %
Jul-19 3lokpn99 CC 115 99.14
Jul-19 3lokpn99 PAYPALL 1 0.86
Jul-19 6jyhikmm CC 180 96.26
Jul-19 6jyhikmm PAYPALL 7 3.74
Aug-19 3lokpn99 CC 108 96.43
Aug-19 3lokpn99 PAYPALL 4 3.57
Aug-19 6jyhikmm CC 114 97.4
Aug-19 6jyhikmm PAYPALL 3 2.56
答:
3赞
Piotr Findeisen
9/25/2019
#1
有不同的方法可能
- 使用 Window 函数
- 带有聚合的 self-JOIN(如 Wojciech 的回答中所示)
窗口函数方法的另一个优点是源数据只读取一次。
SELECT month_year, shopid, payment_method, count,
100e0 * count / sum(count) OVER (
PARTITION BY month_year, shopid
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
AS "%"
FROM ...
(在 Presto 318 上测试)
请参阅 Presto 窗口函数文档 https://trino.io/docs/current/functions/window.html
评论
0赞
justnewbie89
9/25/2019
但是,在运行您的查询之后。我想我需要从窗口功能中删除payment_method。它可以在没有分区的情况下正常工作payment_menthod。再次感谢再次帮助我
0赞
Wojciech Kołacz
9/25/2019
#2
您可以通过以下查询实现此结果:
SELECT s.*, ROUND(s.count / ss.count_summed * 100,2) AS `%`
FROM stack s
JOIN (SELECT s.month_year, s.shopid, SUM(s.count) AS count_summed FROM stack s GROUP BY s.month_year, s.shopid) ss ON ss.month_year = s.month_year AND ss.shopid = s.shopid;
评论