原始数据

________________
|col1 |col2|col3|
________________
|A    | X  | 1  |
________________
|A    | Y  |  5 |
________________
|B    | X  | 2  |
________________
|B    | Y  | 6  |
________________
|C    | Y  | 7  |
________________

期望输出
_______________
|col1| X  | Y |
_______________
|A   | 1  | 5 |
_______________
|B   | 2  | 6 |
_______________
|C   |NULL| 7 |
_______________

最佳答案

示例的crosstab()查询如下所示:

SELECT col1
     , col2 AS "X"
     , col3 AS "Y"
FROM crosstab(
       'SELECT col1 , col2, col3
        FROM   table
        ORDER  BY 1'
       ,$$VALUES ('X'::text), ('Y')$$
 ) AS ct (
   col1 int
 , col2 numeric    -- use actual data type!
 , col3 numeric);

相关答案中的说明和链接:
PostgreSQL Crosstab Query

关于sql - 如何创建查询以将列分割为结果列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42015802/

10-16 02:30