我是Oracle DB的新手。我不确定是否可以这样做。基本上我有一个查询:Oracle将行转换为列和组合重复行
SELECT location,properties,value FROM table_usa
返回此输出:
不知怎的,我想经纬度转化为自己列,还结合初始重复的行。所需的输出:
这甚至可能吗?
我是Oracle DB的新手。我不确定是否可以这样做。基本上我有一个查询:Oracle将行转换为列和组合重复行
SELECT location,properties,value FROM table_usa
返回此输出:
不知怎的,我想经纬度转化为自己列,还结合初始重复的行。所需的输出:
这甚至可能吗?
在oracle
11克(及以上)pivot
是此任务的最通用工具。
的pivot_clause让你写交叉表查询旋转的 行到列,在旋转的过程中聚合数据。
来源
LOCATION |PROPERTIES | VALUE
-----------|-----------|--------
Texas | Latitude | 21.391
Texas | Longitude | 54.12
Detroit | Latitude | 24.23
Detroit | Longitude | 54.23
New York | Latitude | 24.239
New York | Longitude | 55.5
PIVOT选择
select *
from (select Location, Properties, Value
from table_usa)
pivot(
max(Value)
for Properties in ('Latitude' AS LATITUDE,
'Longitude' AS LONGITUDE)
)
order by LATITUDE;
结果
LOCATION | LATITUDE |LONGITUDE
------------|-----------|---------
Texas | 21.391 |54.12
Detroit | 24.23 |54.23
New York | 24.239 |55.5
在Oracle 11g中,您可以尝试PIVOT(请参阅http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)。
在以前的版本,应该工作:
select location,
max(decode(properties, 'Latitude', value, null)) latitude,
max(decode(properties, 'Longitude', value, null)) longitude
from table_usa
group by location
答案是否解决了你的问题? – klashxx