从多行创建单行

时间:2016-04-14 19:44:56

标签: sql oracle

我有一个表,用于存储id,字段标识符以及每行中的值。该表看起来像

create table personInfo(
  personName varchar2(100),
  fieldName varchar2(100),
  fieldValue varchar2(100)
)
/
insert into personInfo values('Adam', 'Address', '123 Cool Street');
insert into personInfo values('Adam', 'Height', '6 foot 1 inch');
insert into personInfo values('Adam', 'Hair Color', 'Blonde');
insert into personInfo values('Bob', 'Address', '451 Fake Street');
insert into personInfo values('Bob', 'Car Model', '2016 Prius');
insert into personInfo values('Bob', 'Hair Color', 'Brown');

现在,如果我知道我想要的字段名称,但是我想将它作为单行而不是行集合返回,我怎样才能将它们归还?所以在这种情况下,我喜欢结果

NAME    ADDRESS           HEIGHT            HAIR COLOR    CAR MODEL
___________________________________________________________________
Adam    123 Cool Street   6 foot 1 inch     Blonde        null
Bob     451 Fake Street   null              Brown         2016 Prius

这是我到目前为止所做的事情

with tab as
 (select personName, fieldName, fieldValue from personInfo where personName = 'Adam')
select *
  from (select (select fieldValue as address from tab where fieldName = 'Address') from dual) t1,
       (select (select fieldValue as height from tab where fieldName = 'Height') from dual),
       (select (select fieldValue as hairColor from tab where fieldName = 'Hair Color') from dual),
       (select (select fieldValue as carModel from tab where fieldName = 'Car Model') from dual);

但这只返回一行,也没有名称。有人知道这是否可行?

1 个答案:

答案 0 :(得分:2)

如果您有一个预定义的字段名称列表,那么您可以试试这个。

    SELECT * FROM
    (SELECT personName, Fieldname, fieldValue
        FROM personInfo) AS t
    pivot
    (
        MAX(t.fieldValue)
        FOR fieldname IN (ADDRESS, HEIGHT, [HAIR COLOR], [CAR MODEL])
    ) AS pvt

如果未预先定义此列表,则可以尝试使用Dynamic Sql创建数据透视表。 Like This.