如何创建查询以将列中的细分作为结果中的列?

时间:2017-02-03 02:34:12

标签: sql postgresql

原始数据

________________
|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 |
_______________

2 个答案:

答案 0 :(得分:1)

您的示例的交叉表()查询如下所示:

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

答案 1 :(得分:0)

一种方法是条件聚合:

select col1,
       max(case when col2 = 'X' then col3 end) as x,
       max(case when col2 = 'Y' then col3 end) as y
from t
group by col1;