【问题标题】:Calculating percentage by group using Teradata使用 Teradata 按组计算百分比
【发布时间】:2020-12-03 16:00:57
【问题描述】:

我正在尝试创建一个表格,显示取决于指标的每个状态的计数百分比。

这是我用来创建新表的数据集示例。

+-------------+-------+-------+
|  Indicator  | State | Count | 
+-------------+-------+-------+
| Registered  | CA    |    25 |
| Registered  | FL    |    12 |
| Total       | CA    |    50 |
| Total       | FL    |    36 |
+-------------+-------+-------+

我正在尝试创建一个新表,其中每个对应行都有一个百分比,如下所示:

+-------------+-------+-------+------------+
|  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 语句中的状态,但我不确定我会如何去做。

最好的方法是什么?

【问题讨论】:

  • 您不只是在 Indicator='Total' 的记录集和其余记录之间进行连接吗?

标签: sql sas teradata


【解决方案1】:

只需将表与自身连接起来。

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
;

【讨论】:

    【解决方案2】:

    你可以使用窗口函数:

    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;
    

    【讨论】:

    • 不确定我是否关注。我在您发布的代码中没有看到窗口函数。我还想知道如何以您发布的方式使用 sum 函数,因为它需要一个数字参数。
    • @dw0000 。 . .它现在就在那里。
    猜你喜欢
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多