开发者

SQL: Key-Value: values in columns?

my table looks like this:

+--------------------------+
| key | value-name | value |
+-----+------------+-------+
| 1   | color      | green |
| 1   | height     | 15    |
| 2   | whatever   | lol   |
+-----+------------+-------+

and i want to flip it so it looks like:

+-----+-------+--------+----------+
| key | color | height | whatever |
+-----+-------+--------+----------+
| 1   | green | 15     | ---      |
| 2   | ---   | ---    | lol      |
+-----+-------+--------+----------+

with sql like:

SELECT key AS k,
  (SELECT color FR开发者_Go百科OM table WHERE key = k),
  (SELECT height FROM table WHERE key = k), ...

... and so on

How can ths be done without creating a subselect for every single value-name (because I believe this is not very fast) ?

My DBS is Oracle 10g.

Edit: I found some examples afterwards, but they all just join and I can't do that because my table has many value-names.


select 
  key
, max( case value-name when 'color' then value else NULL end)      as color
, max( case value-name when 'heght' then value else NULL end)      as height
, max( case value-name when 'whatever' then value else NULL end)   as whatever
from 
  table
group by key


You would first get the values as separate columns, which you can do with a case, then you would group on the key to get them into the same record:

select key, max(color), max(height), max(whatever)
from (
  select
    key,
    case when value-name = 'color' then value else null end as color,
    case when value-name = 'height' then value else null end as height,
    case when value-name = 'whatever' then value else null end as whatever
  from table
) x
group by key


Use conditional CASE statement

CASE column
 WHEN column='a' THEN 'x'
 WHEN column='b' THEN 'y'
END


You can use the pivot function in this way:

SELECT *
FROM 
    table_name
PIVOT ( 
    max(value)
    for value-key
    in (
        'color' as color,
        'height' as height,
        'whatever' as whatever
    )
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜