【发布时间】:2017-08-07 18:42:38
【问题描述】:
我有一张如下所示的表格:
| 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% |
我无法在 total_per_pilot_ind 字段中获取 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值? -
我已编辑帖子以包含整个表格。表格和数据也可以在 rextester 链接中找到。 total_per_pilot_ind 是针对 Pilot_ind 字段(飞行员或非飞行员)的每个值的所有行的计数。通过扩展,pct_pilot_ind_total 计算为 (total_count / total_per_pilot_ind)。
标签: sql postgresql