在Oracle中按组不使用聚合函数或行到列
Posted
技术标签:
【中文标题】在Oracle中按组不使用聚合函数或行到列【英文标题】:Pivot without aggregate function or Row to Columns by group in Oracle 【发布时间】:2016-12-21 09:36:39 【问题描述】:我正在尝试按行类型将行转换为列。 这里给出 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
并在结果中使用选择脚本,我想在 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() 只检索最大数量...
【问题讨论】:
您好,请将图片替换为文字。把它用逗号/制表符作为分隔符,我稍后会格式化它 【参考方案1】: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 |
+-------------+---------------+---------------+
【讨论】:
【参考方案2】:在 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.
【讨论】:
以上是关于在Oracle中按组不使用聚合函数或行到列的主要内容,如果未能解决你的问题,请参考以下文章