簡體   English   中英

如何取消透視表中的多個列

[英]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

我可以使用以下查詢獲取前兩個IDPARAMETERS列:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM