[英]Calculating percentage by group using Teradata
我正在嘗試創建一個表格,顯示每個 state 的計數百分比,具體取決於指標。
這是我用來創建新表的數據集示例。
+-------------+-------+-------+
| 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;
這不起作用,因為我收到一個錯誤:“子查詢評估了不止一行。” 我猜它是因為我沒有考慮到 state 的情況下聲明,但我不確定我會如何 go 。
最好的方法是什么?
您可以使用 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;
只需將表與自身連接即可。
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
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.