簡體   English   中英

SQL:如何根據SQL另一列中的值范圍求和一列?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM