Sql 如何对每种类型的几个列值求和并计算百分比?
我有下面的查询,它给了我三列数据-类型,金额和总数为本周使用周数列 以下是我通过上述查询得到的结果:Sql 如何对每种类型的几个列值求和并计算百分比?,sql,amazon-web-services,amazon-redshift,Sql,Amazon Web Services,Amazon Redshift,我有下面的查询,它给了我三列数据-类型,金额和总数为本周使用周数列 以下是我通过上述查询得到的结果: type amount total --------------------------- PROC1 450 1768 PROC1 900 123 PROC1 450 456 PROC2 8840 99897 PROC2 1490 2223 PROC2 8840
type amount total
---------------------------
PROC1 450 1768
PROC1 900 123
PROC1 450 456
PROC2 8840 99897
PROC2 1490 2223
PROC2 8840 9876
PROC3 1900 23456
PROC3 1600 12498
PROC3 1600 28756
问题陈述
现在,我需要使用以下公式计算每种类型的百分比:
对于每种类型,sumtotal-sumamount/sumamount。
因此,对于PROC1类型,所有“总计”列之和-所有“金额”列之和/所有“金额”列之和。
PROC2和PROC3也是如此。
此外,我还需要额外的总体类型,这将是所有PROC1+PROC2+PROC3值的总和。
最后,我应该看到以下输出:
type sum_amount sum_total percentage
----------------------------------------------
PROC1 1800 2347 0.3038
PROC2 10330 111996 9.841
PROC3 5100 64710 11.688
OVERALL 17230 179053 9.3919
这可以在红移中实现吗?假设您拥有的表被称为my_table。这将是您获得的表的继续:您可以使用with函数继续逻辑:
SELECT *, sum_total/ sum_amounT - 1 percentage
FROM (
SELECT DISTINCT type,
0.0 + SUM(amount) sum_amount,
SUM(total) sum_total
FROM my_table
GROUP BY type)
UNION ALL
SELECT *, sum_total/ sum_amount - 1 percentage
FROM ( SELECT 'overall' type,
0.0 + SUM(amount) sum_amount,
SUM(total) sum_total
FROM my_table)
您可以将其表述为:
with t as (
<your query here>
)
select type, sum(amount) as amount, sum(total) as total,
(sum(total) - sum(amount)) * 1.0 / sum(amount) as ratio
from t
group by type, amount, total
union all
select 'Overall', sum(amount), sum(total),
(sum(total) - sum(amount)) * 1.0 / sum(amount) as ratio
from t;
实际上,这将使整个列排在最后。但是,除非您通过添加订单,否则不能保证这一点
with t as (
<your query here>
)
select type, sum(amount) as amount, sum(total) as total,
(sum(total) - sum(amount)) * 1.0 / sum(amount) as ratio
from t
group by type, amount, total
union all
select 'Overall', sum(amount), sum(total),
(sum(total) - sum(amount)) * 1.0 / sum(amount) as ratio
from t;