PostgreSQL多行作为列

时间:2018-07-27 11:39:04

标签: sql postgresql pivot pivot-table crosstab

我有一张这样的桌子:

| id | name | segment | date_created | question | answer |
|----|------|---------|--------------|----------|--------|
| 1  | John | 1       | 2018-01-01   | 10       | 28     |
| 1  | John | 1       | 2018-01-01   | 14       | 37     |
| 1  | John | 1       | 2018-01-01   | 9        | 83     |
| 2  | Jack | 3       | 2018-03-11   | 22       | 13     |
| 2  | Jack | 3       | 2018-03-11   | 23       | 16     |

我想在一行中显示此信息,将所有问题和答案列为一栏:

| id | name | segment | date_created | question_01 | answer_01 | question_02 | answer_02 | question_03 | answer_03 |
|----|------|---------|--------------|-------------|-----------|-------------|-----------|-------------|-----------|
| 1  | John | 1       | 2018-01-01   | 10          | 28        | 14          | 37        | 9           | 83        |
| 2  | Jack | 3       | 2018-03-11   | 22          | 13        | 23          | 16        |             |           |

已知相同ID的问题/答案数量。最多15个。

我已经尝试使用交叉表,但是它只接受一个值作为类别,并且我可以有2个(问题/答案)。对解决这个问题有帮助吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用row_number在子查询中创建一个数字,然后在主查询中执行汇总函数条件。

SELECT  ID,
        Name,
        segment,
        date_created,
        max(CASE WHEN rn = 1 THEN question END) question_01 ,
        max(CASE WHEN rn = 1 THEN answer END) answer_01  ,
        max(CASE WHEN rn = 2 THEN question END) question_02, 
        max(CASE WHEN rn = 2 THEN answer END) answer_02,
        max(CASE WHEN rn = 3 THEN question END) question_03,
        max(CASE WHEN rn = 3 THEN answer END) answer_03
FROM (
    select *,Row_number() over(partition by ID,Name,segment,date_created order by (select 1)) rn
    from T
) t1
GROUP BY ID,Name,segment,date_created 

sqlfiddle

[结果]

| id | name | segment | date_created | question_01 | answer_01 | question_02 | answer_02 | question_03 | answer_03 |
|----|------|---------|--------------|-------------|-----------|-------------|-----------|-------------|-----------|
|  1 | John |       1 |   2018-01-01 |           1 |        28 |          14 |        37 |           9 |        83 |
|  2 | Jack |       3 |   2018-03-11 |          22 |        13 |          23 |        16 |      (null) |    (null) |