我们说我有一张包含收入和状态列的订单的表格。我想按收入组对订单进行分组(按10的增量分组),并获取其各自收入组中其状态列设置为1的百分比。我认为窗口函数是可行的方法,但where语句限制列,以便我最终只得到status == 1的列。
最终结果类似于:10 | 76%
,20 | 50%
等。
SELECT CASE
WHEN revenue between 1 and 10 then 10
WHEN revenue between 10 and 20 then 20
WHEN revenue between 20 and 30 then 30
WHEN revenue between 30 and 40 then 40
WHEN revenue between 40 and 50 then 50
else 60
END as revgroup,
COUNT(*) / CAST(SUM(count(*)) over (partition by CASE
WHEN revenue between 1 and 10 then 10
WHEN revenue between 10 and 20 then 20
WHEN revenue between 20 and 30 then 30
WHEN revenue between 30 and 40 then 40
WHEN revenue between 40 and 50 then 50
else 60 END) as float) as percentage
from "order"
where "order".status = 1
group by revgroup
答案 0 :(得分:0)
子句PARTITION BY在您的情况下过多,每个分区都是使用子句GROUP BY
创建的SELECT CASE
WHEN revenue between 1 and 10 then 10
WHEN revenue between 10 and 20 then 20
WHEN revenue between 20 and 30 then 30
WHEN revenue between 30 and 40 then 40
WHEN revenue between 40 and 50 then 50
else 60
END as revgroup,
COUNT(*) * 1.0 / SUM(COUNT(*)) OVER () as percentage
from "order"
where "order".status = 1
group by revgroup