[英]How to structure subqueries/CTEs to replace nested aggregate functions?
I am trying to find out what percent of the 'amt' values belongs to each of the 'percent' buckets. 我试图找出'amt'值的百分比属于每个'百分比'桶。
Example Data: 示例数据:
amt | pct
5 | .5
10 | .6
15 | 1
20 | .8
Desired Results: 期望的结果:
pctAMT | PCTrange
.3 | <65
.4 | 75-84
.3 | 100+
I've tried using a nested aggregate function, and also trying to use the total as a single value. 我尝试使用嵌套聚合函数,并尝试将总计作为单个值。 However, I'm running into errors. 但是,我遇到了错误。 I think I have to re-structure the query as a CTE or subquery but I'm not sure how. 我想我必须将查询重新构造为CTE或子查询,但我不确定如何。
SELECT SUM(amt)/(SUM(amt) OVER()) AS pctAMT,
CASE WHEN percent < .65 then ' <65'
WHEN .65 <= percent AND percent <.75 then '65-74'
WHEN .75 <= percent AND percent <.85 then '75-84'
WHEN .85 <= percent AND percent <.95 then '85-94'
WHEN .95 <= percent AND percent <1.00 then '95-99'
WHEN .100 <= percent then ' 100+'
END PCTrange
FROM table
WHERE date = TO_DATE('2016-04-01','YYYY-MM-DD')
GROUP BY PCTrange
ORDER BY PCTrange;
ERROR [HY000] ERROR: Attribute LN_HIST.LN_FNCL_RPTG_UPB must be GROUPed or used in an aggregate function
I would expect something like this: 我希望这样的事情:
SELECT (CASE WHEN percent < 0.65 then ' <65'
WHEN percent < 0.75 then '65-74'
WHEN percent < 0.85 then '75-84'
WHEN percent < 0.95 then '85-94'
WHEN percent < 1.00 then '95-99'
ELSE ' 100+'
END) as PCTrange,
SUM(amt)/ SUM(SUM(amt)) OVER () AS pctAMT
FROM table
WHERE date = '2016-04-01'
GROUP BY PCTrange
ORDER BY PCTrange;
The important change is SUM(SUM())
-- adding up the sums for division. 重要的变化是SUM(SUM())
- 加总除法的总和。
I also simplified the CASE
expression. 我还简化了CASE
表达式。 The clauses are evaluated in order, so you can take advantage of that. 条款按顺序进行评估,因此您可以利用它。 The date comparison is also simpler. 日期比较也比较简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.