简体   繁体   English

在 Postgres 9.6 中创建 pivot 表

[英]Create pivot table in Postgres 9.6

I am having trouble creating the desired output using SQL.我无法使用 SQL 创建所需的 output。 I have an events table, that holds a record for every event taken by each candidate, as so:我有一个事件表,其中包含每个候选人参加的每个事件的记录,如下所示:

| id | asmnt   | timestamp           | score |
|----|---------|---------------------|-------|
| 1  | pushups | 2020-06-21 12:31:12 | 34    |
| 1  | situps  | 2020-06-21 13:31:12 | 65    |
| 1  | run     | 2020-06-22 12:31:12 | 901   |
| 1  | pullups | 2020-06-21 14:31:12 | 15    |
| 2  | pushups | 2020-06-21 12:31:12 | 13    |
| 2  | situps  | 2020-06-21 13:31:12 | 21    |
| 2  | run     | 2020-06-22 12:31:12 | 1401  |
| 2  | pullups | 2020-06-21 14:31:12 | 3     |
| 2  | pushups | 2020-06-23 12:31:12 | 31    |
| 2  | situps  | 2020-06-23 13:31:12 | 45    |
| 2  | run     | 2020-06-24 12:31:12 | 1101  |
| 2  | pullups | 2020-06-23 14:31:12 | 13    |

Can I create a pivot table from this?我可以从中创建一个 pivot 表吗? I tried to use the crosstab extension, but due to the fact that each group (by id) will not be the same size, I am getting an error (not surprising).我尝试使用交叉表扩展,但由于每个组(按 id)的大小不同,我收到一个错误(不足为奇)。 It is important to retain order (asmnt), as well as order by timestamp.保留顺序 (asmnt) 以及按时间戳排序很重要。

This is the output that I would like:这是我想要的 output:

| id | pushups | situps | run | pullups |
|----|---------|--------|-----|---------|
| 1  | 34      | 65     | 901 |   15    |
| 2  | 31      | 45     | 1101|   13    |

Here is the SQL that I have tried (asmnt: APFPS, APFSU, APF2M or APFPL):这是我尝试过的 SQL(asmnt:APFPS、APFSU、APF2M 或 APFPL):

select *
from crosstab('select brandi_id, asmnt_code, score
from event
where left(asmnt_code,3) = ''APF''
order by brandi_id, asmnt_code, event_timestamp') 
    as events(brandi_id INTEGER,APF2M TEXT,APFPL TEXT,APFPS TEXT,APFSU TEXT,score INTEGER);

Using a filtered aggregate is usually the easiest way:使用过滤聚合通常是最简单的方法:

select id, 
       count(*) filter (were asmnt = 'pushups') as pushups,
       count(*) filter (were asmnt = 'situps') as situps,
       count(*) filter (were asmnt = 'run') as run,
       count(*) filter (were asmnt = 'pullups') as pullups
from event
group by id;

I understand that you want the score of the latest asmnt per id , in a pivoted resultset.我了解您希望在旋转结果集中获得每个id的最新asmntscore

If so, you can use distinct on to get the latest record per group, and then conditional aggregation to pivot:如果是这样,您可以使用distinct on获取每组的最新记录,然后将条件聚合到 pivot:

select
    id,
    max(score) filter(where asmnt = 'pushups') pushups,
    max(score) filter(where asmnt = 'situps') situps,
    max(score) filter(where asmnt = 'run') run,
    max(score) filter(where asmnt = 'pullups') pullups
from (
    select distinct on (id, asmnt) e.*
    from event e
    order by id, asmnt, timestamp desc
) e
group by id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM