使用 Teradata 按组计算百分比
Calculating percentage by group using Teradata
我正在尝试创建一个 table 来显示每个州依赖于指标的计数百分比。
这是我用来创建新 table 的数据集示例。
+-------------+-------+-------+
| Indicator | State | Count |
+-------------+-------+-------+
| Registered | CA | 25 |
| Registered | FL | 12 |
| Total | CA | 50 |
| Total | FL | 36 |
+-------------+-------+-------+
我正在尝试创建一个新的 table,每个对应的行都有一个百分比,如下所示:
+-------------+-------+-------+------------+
| Indicator | State | Count | Percentage |
+-------------+-------+-------+------------+
| Registered | CA | 25 | 50 |
| Registered | FL | 12 | 33.3 |
| Total | CA | 50 | . |
| Total | FL | 36 | . |
+-------------+-------+-------+------------+
到目前为止,我已经尝试执行以下查询:
select indicator, state, count
, case when (select count from table where indicator='Registered') * 100 / (select count from table where indicator='Total')
when indicator = 'Total' then . end as Percentage
from table;
这不起作用,因为我得到一个错误:“子查询评估了不止一行。”我猜是因为我没有考虑 case when 语句中的状态,但我不确定我会怎么做。
最好的方法是什么?
您可以使用 window 函数:
select t.*,
(case when indicator <> 'Total'
then count * 100.0 / sum(case when indicator = 'Total' then indicator end) over (partition by state)
end) as percentage
from t;
只需加入 table 本身即可。
select a.indicator, a.state, a.count
, case when (indicator='Total') then null
else 100 * a.count/b.count
end as Percentage
from table a
inner join (select state,count from table where indicator='Total') b
on a.state = b.state
;
我正在尝试创建一个 table 来显示每个州依赖于指标的计数百分比。
这是我用来创建新 table 的数据集示例。
+-------------+-------+-------+
| Indicator | State | Count |
+-------------+-------+-------+
| Registered | CA | 25 |
| Registered | FL | 12 |
| Total | CA | 50 |
| Total | FL | 36 |
+-------------+-------+-------+
我正在尝试创建一个新的 table,每个对应的行都有一个百分比,如下所示:
+-------------+-------+-------+------------+
| Indicator | State | Count | Percentage |
+-------------+-------+-------+------------+
| Registered | CA | 25 | 50 |
| Registered | FL | 12 | 33.3 |
| Total | CA | 50 | . |
| Total | FL | 36 | . |
+-------------+-------+-------+------------+
到目前为止,我已经尝试执行以下查询:
select indicator, state, count
, case when (select count from table where indicator='Registered') * 100 / (select count from table where indicator='Total')
when indicator = 'Total' then . end as Percentage
from table;
这不起作用,因为我得到一个错误:“子查询评估了不止一行。”我猜是因为我没有考虑 case when 语句中的状态,但我不确定我会怎么做。
最好的方法是什么?
您可以使用 window 函数:
select t.*,
(case when indicator <> 'Total'
then count * 100.0 / sum(case when indicator = 'Total' then indicator end) over (partition by state)
end) as percentage
from t;
只需加入 table 本身即可。
select a.indicator, a.state, a.count
, case when (indicator='Total') then null
else 100 * a.count/b.count
end as Percentage
from table a
inner join (select state,count from table where indicator='Total') b
on a.state = b.state
;