Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivot without aggregate function or Row to Columns by group in Oracle

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...

like image 411
assyl.d Avatar asked Feb 06 '23 11:02

assyl.d


1 Answers

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       |
+-------------+---------------+---------------+
like image 98
David דודו Markovitz Avatar answered Feb 08 '23 02:02

David דודו Markovitz