【问题标题】:calculate a derived column in sql在sql中计算派生列
【发布时间】:2021-08-20 23:12:46
【问题描述】:

我有一个如下查询,它会生成下表:-

select * from temp_3

bucket  values
OTIF+2  319
OTIF    24987              
null    1347               
OTIF+>2 515
OTIF+1  552

现在我需要这些值占我编写以下查询的值总和的百分比:-

select sum(values) as total into temp_1 from temp_3
select bucket, (values/(select total from temp_1)) as score from temp_3

但这导致了以下结果:-

bucket  values
OTIF+2  0
OTIF    0              
null    0               
OTIF+>2 0
OTIF+1  0

谁能告诉我我们如何有效地将其转换为百分比形式?以及我哪里出错了?

【问题讨论】:

  • 整数运算,5/20 产生 0。将其转换为十进制,例如 values * 1.0/(select total from temp_1)

标签: sql derived-column


【解决方案1】:

使用窗口函数:

select bucket, value,
       value * 1.0 / sum(value) over ()
from t;

【讨论】:

    【解决方案2】:
    select sum(values) as total into temp_1 from temp_3
    select bucket, (values * 100) /total as score from temp_3, temp_1
    

    或者只是

    select bucket, (values * 100) /sum(values) as score from temp_3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 2013-09-28
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      相关资源
      最近更新 更多