根据值转置 SQL select
Transpose SQL select based on values
给定 table:
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');
我怎样才能select关注:
| obj | type A | type B | type C|
this foo bar asd
that qwe buz NULL
这不是 "pivot all rows to cols" 个问题的重复;这里的区别是条件 - 值可以根据类型转到多个列。
尝试
select obj, [type A], [type B], [type C]
from test
pivot (max(val) for prop in ([type A], [type B], [type C])) B
给定 table:
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');
我怎样才能select关注:
| obj | type A | type B | type C|
this foo bar asd
that qwe buz NULL
这不是 "pivot all rows to cols" 个问题的重复;这里的区别是条件 - 值可以根据类型转到多个列。
尝试
select obj, [type A], [type B], [type C]
from test
pivot (max(val) for prop in ([type A], [type B], [type C])) B