Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

sql - "pivot" table Oracle - how to change row items into columns

I have the following simple example:

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;

The thing is that I need to "pivot" the table to get items as column names with values as values and everything grouped together (row with unique car name and no null values in cells). Hence I wrote "pivot", because classic pivoting (DECODE) leads to different result - decreasing skew values in cells and a lot of null values. So it would looks like this

car      wheels color  price
-------- ------ ------ -----
bmw           4    red     5
lambo         5 yellow     7
mercedes      4  black     6

So the question:

Should I do this via procedures or is there any more elegant solution? Procedure would be following (in pseudocode):

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*/

OK, code seems simple. But having more than half a milion of records and 15 items, and updating the table once a hour may lead to real performance problems.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the query below;-

  select * from
  (select cars, item,value from carTable) 
  pivot(max(value) for item in ('wheels', 'color', 'price'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...