我正在尝试按行的类型将行转换为列 这里给出了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
并在结果中使用select脚本,我想在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
我试过PIVOT。但必须有汇总的功能 聚合函数MAX()只检索最大量...
答案 0 :(得分:6)
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 |
+-------------+---------------+---------------+
答案 1 :(得分:1)
在Oracle 11.1及更高版本中,您可以对PIVOT
运算符执行相同操作 - 但首先必须将行与row_number()
进行区分(与Dudu的解决方案相同) 。 PIVOT
解决方案如下所示:
with
table_1 ( city, amount, type_id ) as (
select 'Moscow' , 158000, 1 from dual union all
select 'New York' , 94500, 1 from dual union all
select 'Moscow' , 1478000, 2 from dual union all
select 'Los Angeles', 162000, 2 from dual union all
select 'New York' , 5500000, 2 from dual union all
select 'Los Angeles', 35400, 1 from dual union all
select 'Moscow' , 741200, 1 from dual
)
-- end of test data; SQL query begins below this line
select city, type_1, type_2
from ( select city, amount, type_id,
row_number() over (partition by city, type_id order by amount) as rn
from table_1
)
pivot ( min(amount) for type_id in (1 as type_1, 2 as type_2) )
order by city, type_1, type_2 -- ORDER BY is optional
;
CITY TYPE_1 TYPE_2
----------- ---------- ----------
Los Angeles 35400 162000
Moscow 158000 1478000
Moscow 741200
New York 94500 5500000
4 rows selected.