我有以下简单示例:
CREATE TABLE Cars ( Cars, Item, Value ) AS
SELECT 'bmw', 'wheels', '4' FROM DUAL UNION ALL
SELECT 'bmw', 'color', 'red' FROM DUAL UNION ALL
SELECT 'bmw', 'price', '5' FROM DUAL UNION ALL
SELECT 'mercedes', 'wheels', '4' FROM DUAL UNION ALL
SELECT 'mercedes', 'color', 'black' FROM DUAL UNION ALL
SELECT 'lambo', 'wheels', '5' FROM DUAL UNION ALL
SELECT 'lambo', 'color', 'yellow' FROM DUAL UNION ALL
SELECT 'lambo', 'price', '7' FROM DUAL UNION ALL
SELECT 'mercedes', 'price', '6' FROM DUAL;
问题是我需要“转动”表格以将项目作为列名称,将值作为值并将所有内容组合在一起(具有唯一车名的行和单元格中没有空值)。因此我写了“pivot”,因为经典的旋转(DECODE)会导致不同的结果 - 减少单元格中的偏斜值和大量的空值。所以它看起来像这样
car wheels color price
-------- ------ ------ -----
bmw 4 red 5
lambo 5 yellow 7
mercedes 4 black 6
所以问题:
我应该通过程序这样做还是有更优雅的解决方案?程序将遵循(伪代码):
1. create table cars2 /*collumns are known in before, wheels/color/price*/
2. get the distinct names of the cars and insert them into collection /*eg nested table*/
3. for each car do
insert into table cars2
values per item /*looping items and inserting corresponding values*/
好的,代码看起来很简单。但拥有超过五十万的记录和15个项目,并且每小时更新一次表可能会导致真正的性能问题。
答案 0 :(得分:0)
尝试以下查询; -
select * from (select cars, item,value from carTable) pivot(max(value) for item in ('wheels', 'color', 'price'))
答案 1 :(得分:0)
(?<!\w)
<强>输出强>:
(?!\w)