给出表:
create table test(obj varchar(99), prop varchar(99), val varchar(99));
insert into test (obj , prop , val ) values ('this', 'type A', 'foo');
insert into test (obj , prop , val ) values ('this', 'type B', 'bar');
insert into test (obj , prop , val ) values ('this', 'type C', 'asd');
insert into test (obj , prop , val ) values ('that', 'type B', 'buz');
insert into test (obj , prop , val ) values ('that', 'type A', 'qwe');
如何选择以下内容:
| obj | type A | type B | type C|
this foo bar asd
that qwe buz NULL
这不是“将所有行转移到cols”问题的重复;这里的区别是条件 - 值可以根据类型转到几列。
答案 0 :(得分:1)
尝试
select obj, [type A], [type B], [type C]
from test
pivot (max(val) for prop in ([type A], [type B], [type C])) B