I recently switched from SQL Server to PostgreSQL and trying to find equivalent of pivot function. I am not able to get a desired output using crosstab which I was able to achieve using SQL Server.
Sample data.
CREATE TABLE loc
AS
SELECT location, sub_location, step, amount
FROM ( VALUES
( 100 , '100_A', 'step_1', 2 ),
( 100 , '100_A', 'step_2', 7 ),
( 100 , '100_A', 'step_3', 6 ),
( 100 , '100_B', 'step_1', 5 ),
( 100 , '100_B', 'step_2', 8 ),
( 100 , '100_B', 'step_3', 9 )
) AS t(location, sub_location, step, amount);
I am trying to achieve this below result set.
Location Sub_location Step_1 Step_2 Step_3
-------- ------------ ------ ------ ------
100 100_A 2 7 6
100 100_B 5 8 9
I could easily achieve this is MS SQL. And my crosstab query,
Select * from crosstab
(
'select location, sub_location, step, amount from loc',
'select distinct step from loc'
)
as final_result(location varchar,sub_location varchar, step_1 int, step_2 int, step_3 int);
I only see one row instead of two row. Anyway to overcome this limitation in postgres.