将三列转换为行的百分比

wb1gzix0  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(441)

我不知道如何用最好的语言来表达这一点,但下面是我的数据,我正试图建立一个查询,将每一列输出为现金、计划支付、政府三项的百分比
列数据:

输出如下:

我试过这个

select str_nbr ,(sum(cast(planpay as float) / (sum(cast (planpay as float) + sum (cast (cash as float) + sum (cast (govt as float))) 

from Insurance where str_nbr in ( '15308') group by str_nbr
ltqd579y

ltqd579y1#

你可以用除法。如果不想重复计算,请使用 apply :

select t.str_nbr,
       t.cash * 100.0 / v.total as cash_pct,
       t.planpay * 100.0 / v.total as planpay_pct,
       t.govt * 100.0 / v.total as govt_pct
from t cross apply
     (values (cash + planpay + govt)) v(total)

请注意,SQLServer执行整数除法。如果值是整数 1 / 20 而不是 0.5 . 这个 * 100.0 解决了这个问题。

xmjla07d

xmjla07d2#

只需执行与excel中相同的逻辑,但要使用t-sql。避免重复使用cte

with cte as (
  select
    str_nbr,
    CASH,
    PLANPAY,
    GOVT,
    CASH + PLANPAY + GOVT as total
  from Insurance
)
select
  str_nbr as store,
  100.0 * CASH    / total as cash,
  100.0 * PLANPAY / total as planpay,
  100.0 * GOVT    / total as govt
from cte;

相关问题