如何取消透视表中的多个列

时间:2019-01-21 04:10:46

标签: sql sql-server

我有一个具有以下结构的表,我需要取消透视输出,以便每个ID的{​​{1}}每行一行,它对应的PARAMETER

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)

稍后,我还需要过滤,以便仅获得那些具有 1级和2级的行。因此输出必须是

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

我可以使用以下查询获取前两个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

有人可以让我知道如何获取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 列吗?

3 个答案:

答案 0 :(得分:2)

只需添加值列:

select ID,[parameters], [rating] = value 
from RATINGS
unpivot
(
[value] for [PARAMETERS] in (PARAMETER1,PARAMETER2,PARAMETER3,PARAMETER4)
) unpvt
where value in (1,2);

答案 1 :(得分:1)

您可以使用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

答案 2 :(得分:1)

我会使用CROSS APPLY

SELECT r.id, rr.PARAMETERS, rr.RATING
FROM ratings r CROSS APPLY
     ( VALUES ([PARAMETERS1], 'PARAMETERS1'), . . .  ) rr(RATING, PARAMETERS)
ORDER BY r.id;