1

Original data

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

desired output

_______________
|col1| X  | Y |
_______________
|A   | 1  | 5 |
_______________
|B   | 2  | 6 |
_______________
|C   |NULL| 7 |
_______________
Ranjith Ramachandra
  • 10,399
  • 14
  • 59
  • 96

2 Answers2

1

A crosstab() query for your example would look like this:

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);

Explanation and links in this related answer: PostgreSQL Crosstab Query

Community
  • 1
  • 1
Vijay Mistry
  • 157
  • 5
  • This sort of looks like what I want. However looks like 'X' and 'Y' need to be hard coded which is something I am not so sure about. I will figure it out though. – Ranjith Ramachandra Feb 03 '17 at 06:41
0

One method is conditional aggregation:

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786