我有一个KVP Key值对表,需要sql才能使它成为关系结构......!

时间:2010-03-20 10:33:30

标签: sql oracle

我有一张KVP表,结构是ID,Key,Value。

以下是一些示例值...

ID, KEY,       VALUE
---------------------
 1, STATUS,    TRUE
 1, AGE GROUP, 10
 1, TRAVEL,    Y
 2, STATUS,    FALSE
 2, AGE GROUP, 20
 2, TRAVEL,    N

我希望将这些值转换为......

ID, STATUS, AGE GROUP, TRAVEL
------------------------------
 1, TRUE,   10,        Y
 2, FALSE,  20,        N

我已经阅读过有关交叉表/数据透视表的内容,但是我无法进行可以提供上述输出的查询。在SQL中是否有任何方法使我的输出看起来像上面的例子?

3 个答案:

答案 0 :(得分:2)

假设Oracle基于标记,那么

SELECT DISTINCT id
  , MAX(CASE key WHEN 'STATUS' THEN value ELSE null END) OVER (PARTITION BY id) status
  , MAX(CASE key WHEN 'AGE GROUP' THEN value ELSE null END) OVER (PARTITION BY id) age_grp
  , MAX(CASE key WHEN 'TRAVEL' THEN value ELSE null END) OVER (PARTITION BY id) travel
FROM kvp
ORDER BY id;

答案 1 :(得分:0)

可能有优化,但这有效(在SQLite和MySQL中测试)

select stat.id as id, status, age_group, travel from 
(select id, Value as status from kvp
where Key = 'STATUS') as stat JOIN
(select id, Value as age_group from kvp
where Key = 'AGE GROUP') as age on stat.id = age.id JOIN
(select id, Value as travel from kvp
where Key = 'TRAVEL') as trav on stat.id = trav.id;

编辑修复可能的歧义。

答案 2 :(得分:0)

select
    min(decode(KEY, 'ID',        VALUE, null)) ID,
    min(decode(KEY, 'STATUS',    VALUE, null)) STATUS,
    min(decode(KEY, 'AGE GROUP', VALUE, null)) AGE_GROUP,
    min(decode(KEY, 'TRAVEL',    VALUE, null)) TRAVEL
from
    KVP