我有一個表,看起來像這樣:當它是GROUP BY中多個字段之一時,如何彙總單個字段的數據?
| loc_id | pilot_ind | last_form_step_completed |
|--------|-----------|--------------------------|
| 9988 | non-pilot | 1 |
| 9988 | non-pilot | 1 |
| 9988 | non-pilot | 2 |
| 9988 | non-pilot | 2 |
| 9988 | non-pilot | 2 |
| 9988 | non-pilot | 3 |
| 9988 | non-pilot | 3 |
| 9988 | non-pilot | 4 |
| 9988 | non-pilot | 4 |
| 1122 | non-pilot | 1 |
| 1122 | non-pilot | 2 |
| 1122 | non-pilot | 2 |
| 1122 | non-pilot | 2 |
| 1122 | non-pilot | 3 |
| 1122 | non-pilot | 4 |
| 1122 | non-pilot | 5 |
| 5544 | pilot | 1 |
| 5544 | pilot | 1 |
| 5544 | pilot | 2 |
| 5544 | pilot | 2 |
| 5544 | pilot | 2 |
| 5544 | pilot | 3 |
| 5544 | pilot | 3 |
| 5544 | pilot | 4 |
| 5544 | pilot | 4 |
| 5544 | pilot | 5 |
| 5544 | pilot | 5 |
| 5544 | pilot | 5 |
| 5544 | pilot | 5 |
| 5544 | pilot | 5 |
| 3344 | pilot | 1 |
| 3344 | pilot | 2 |
| 3344 | pilot | 2 |
| 3344 | pilot | 3 |
| 3344 | pilot | 3 |
| 3344 | pilot | 3 |
| 3344 | pilot | 4 |
| 3344 | pilot | 4 |
| 3344 | pilot | 4 |
| 3344 | pilot | 5 |
| 3344 | pilot | 5 |
| 3344 | pilot | 5 |
我要總結一下這樣的:
| pilot_ind | last_step_compl | total_count | total_per_pilot_ind | pct_pilot_ind_total |
|-----------|-----------------|-------------|---------------------|---------------------|
| non-pilot | 1 | 3 | 16 | 18.8% |
| non-pilot | 2 | 6 | 16 | 37.5% |
| non-pilot | 3 | 3 | 16 | 18.8% |
| non-pilot | 4 | 3 | 16 | 18.8% |
| non-pilot | 5 | 1 | 16 | 6.3% |
| pilot | 1 | 3 | 26 | 11.5% |
| pilot | 2 | 5 | 26 | 19.2% |
| pilot | 3 | 5 | 26 | 19.2% |
| pilot | 4 | 5 | 26 | 19.2% |
| pilot | 5 | 8 | 26 | 30.8% |
我遇到麻煩了pilot_ind分組的總的total_per_pilot_ind場 - 我曾嘗試使用OVER(PARTITION BY),但結果不正確,因爲GROUP BY子句中有兩個字段。 這裏是一個鏈接到示例數據和當前的嘗試:http://rextester.com/PCE62786
select
r.pilot_ind
,r.last_form_step_completed
,count(*) total_count
,count(*) over()
from
results r
group by
r.pilot_ind
,r.last_form_step_completed
order by 1,2
編輯:有沒有辦法在一個查詢中這樣做嗎?
如何計算'total_per_pilot_ind'列中的'16'和'26'值在你的例子中? – krokodilko
我已編輯帖子以包含整個表格。表格和數據也可以在rextester鏈接中找到。 total_per_pilot_ind是pilot_ind字段(導頻或非導頻)的每個值的所有行的計數。通過擴展,pct_pilot_ind_total被計算爲(total_count/total_per_pilot_ind)。 – psrpsrpsr