I am trying to transform rows to columns by type of row.
Here given Table_1 Table_1
           Table_1
CITY            AMOUNT      TYPE_ID
Moscow         158000          1
New York       94500           1
Moscow         1478000         2
Los Angeles    162000          2
New York       5500000         2
Los Angeles    35400           1
Moscow         741200          1
and with select script in result I want to take like in Table_2 Table_2
            Table_2
CITY           TYPE_1_AMOUNT       TYPE_2_AMOUNT
Moscow           158000               1478000
Moscow           741200                  NULL
New York         94500                5500000
Los Angeles      35400                162000
I tried with PIVOT. but there must be aggregate func.
Aggregate function MAX() retrieves just max amount... 
select      city
           ,min (case type_id when 1 then amount end)   as type_1_amount
           ,min (case type_id when 2 then amount end)   as type_2_amount
from       (select      city,type_id,amount
                       ,row_number () over 
                        (
                            partition by    city,type_id
                            order by        amount
                        ) as rn
            from        Table_1
            )
group by    city
           ,rn
order by    city
           ,rn               
+-------------+---------------+---------------+
| CITY        | TYPE_1_AMOUNT | TYPE_2_AMOUNT |
+-------------+---------------+---------------+
| Los Angeles | 35400         | 162000        |
+-------------+---------------+---------------+
| Moscow      | 158000        | 1478000       |
+-------------+---------------+---------------+
| Moscow      | 741200        | (null)        |
+-------------+---------------+---------------+
| New York    | 94500         | 5500000       |
+-------------+---------------+---------------+
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With