[英]SQL : How to sum a column based on the range of value in another column in SQL?
以下是我可用的数据:
rate Fee
0.12 48,599
0.29 80,718
0.37 94,110
0.44 75,289
0.62 79,236
0.85 99,210
现在,我需要按以下方式进行总结:
Rate_classification Fee
Low Rate (0 -to- 0.25) 48,599
Moderate rate (0.25 -to- 0.75) 329,353
High rate (0.75 -to- 1.00) 99,210
谢谢。
在派生表中使用case
表达式对费率进行分类。 GROUP BY
结果GROUP BY
:
select rate_class, sum(fee)
from
(
select case when rate < 0.25 then 'low rate'
when rate < 0.75 then 'medium rate'
else 'high rate'
end as rate_class,
Fee
from tablename
) dt
group by rate_class
你可以尝试下面的方式
select case when rate>=0 and rate<.25 then 'Low_Rate'
case when rate>=.25 and rate<.75 then 'Moderate'
else 'High' end as Rate_classification,
sum(fee)
from your_table group by Rate_classification
这是一个替代解决方案,其中包括针对该问题的cte结构,同时尊重jarlh的回答。
;with cte (Rateclass,rate,fee) as (
select Rateclass = (case when rate >=0.0 and rate < 0.25 then LowRate
when rate >=0.25 and rate < 0.75 then ModerateRate
when rate >=0.75 and rate < 1.0 then HighRate end),
rate,
fee
from table
)
select Rateclass, sum(fee)
from cte
group by Rateclass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.