[英]How to unpivot multiple columns in same table
我有一个具有以下结构的表,我需要取消透视输出,以便每个PARAMETER
每个ID
获得一行,并且它对应于RATINGS
create table RATINGS(ID INT,PARAMETER1 INT,PARAMETER2 INT,PARAMETER3 INT,PARAMETER4 INT)
insert into RATINGS values(1000,1,3,2,1)
insert into RATINGS values(1002,2,3,3,2)
insert into RATINGS values(1007,3,3,2,1)
insert into RATINGS values(1015,1,3,1,3)
insert into RATINGS values(1019,3,2,1,1)
预期产量:
ID PARAMETERS RATING
1000 PARAMETER1 1
1000 PARAMETER2 3
1000 PARAMETER3 2
1000 PARAMETER4 1
1002 PARAMETER1 2
1002 PARAMETER2 3
1002 PARAMETER3 3
1002 PARAMETER4 2
1007 PARAMETER1 3
1007 PARAMETER2 3
1007 PARAMETER3 2
1007 PARAMETER4 1
1015 PARAMETER1 1
1015 PARAMETER2 3
1015 PARAMETER3 1
1015 PARAMETER4 3
1019 PARAMETER1 3
1019 PARAMETER1 2
1019 PARAMETER1 1
1019 PARAMETER1 1
稍后,我还需要进行过滤,以便仅获得评级为1和2的那些行。 所以输出必须是
ID PARAMETERS RATING
1000 PARAMETER1 1
1000 PARAMETER3 2
1000 PARAMETER4 1
1002 PARAMETER1 2
1002 PARAMETER4 2
1007 PARAMETER3 2
1007 PARAMETER4 1
1015 PARAMETER1 1
1015 PARAMETER3 1
1019 PARAMETER1 2
1019 PARAMETER1 1
1019 PARAMETER1 1
我可以使用以下查询获取前两个ID
和PARAMETERS
列:
select ID,[parameters] from RATINGS
unpivot
(
[value] for [PARAMETERS] in (PARAMETER1,PARAMETER2,PARAMETER3,PARAMETER4)
) unpvt
OUTPUT:
ID PARAMETERS
1000 PARAMETER1
1000 PARAMETER2
1000 PARAMETER3
1000 PARAMETER4
1002 PARAMETER1
1002 PARAMETER2
1002 PARAMETER3
1002 PARAMETER4
1007 PARAMETER1
1007 PARAMETER2
1007 PARAMETER3
1007 PARAMETER4
1015 PARAMETER1
1015 PARAMETER2
1015 PARAMETER3
1015 PARAMETER4
1019 PARAMETER1
1019 PARAMETER2
1019 PARAMETER3
1019 PARAMETER4
有人可以让我知道如何获得“ Rating
列吗?
只需添加值列:
select ID,[parameters], [rating] = value
from RATINGS
unpivot
(
[value] for [PARAMETERS] in (PARAMETER1,PARAMETER2,PARAMETER3,PARAMETER4)
) unpvt
where value in (1,2);
您可以使用UNION取消透视
select id, 'PARAMETERS1' as parameters, parameter1 as rating
from ratings
union
select id, 'PARAMETERS2' as parameters, parameter2 as rating
from ratings
union
select id, 'PARAMETERS3' as parameters, parameter3 as rating
from ratings
union
select id, 'PARAMETERS4' as parameters, parameter4 as rating
from ratings
order by id, parameters
http://www.sqlfiddle.com/#!9/421f05/7
然后第二部分
with parmratings as (
select id, 'PARAMETERS1' as parameters, parameter1 as rating
from ratings
union
select id, 'PARAMETERS2' . . .
)
select * from parmratings where rating < 3
我会使用CROSS APPLY
:
SELECT r.id, rr.PARAMETERS, rr.RATING
FROM ratings r CROSS APPLY
( VALUES ([PARAMETERS1], 'PARAMETERS1'), . . . ) rr(RATING, PARAMETERS)
ORDER BY r.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.