本文介紹了SQL server 使用 unpivot 函數(shù)的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
限時(shí)送ChatGPT賬號(hào)..
您將如何使用 SQL 獲得以下輸出?
How would you obtain the following output using SQL?
Type: Value Type2 Value2
p_01 1 ofpk_01 1
p_02 2 ofpk_02 2
p_03 3 ofpk_03 3
表結(jié)構(gòu)
create table test(p_01 int,
p_02 int,
p_03 int,
ofpk_01 int,
ofpk_02 int,
ofpk_03 int)
SQL 小提琴鏈接
這是否可以使用 unpivot 功能?這是我到目前為止所得到的:
Is this possible with unpivot function? here is what I've got so far:
推薦答案
另一種解決方案是使用CROSS APPLY
:
Another solution is to use CROSS APPLY
:
SELECT ca.*
FROM dbo.Test x
CROSS APPLY
(
SELECT 'p_01' AS Type1, x.p_01 AS Value1, 'ofpk_01' AS Type2, x.ofpk_01 AS Value2 UNION ALL
SELECT 'p_02' AS Type1, x.p_02 AS Value1, 'ofpk_02' AS Type2, x.ofpk_02 AS Value2 UNION ALL
SELECT 'p_03' AS Type1, x.p_03 AS Value1, 'ofpk_03' AS Type2, x.ofpk_03 AS Value2
) ca;
SQL 小提琴
或者如果 2008+ 可以縮短為
Or if 2008+ this can be shortened to
SELECT ca.*
FROM dbo.Test x
CROSS APPLY
(VALUES
('p_01', x.p_01, 'ofpk_01', x.ofpk_01),
('p_02', x.p_02, 'ofpk_02', x.ofpk_02),
('p_03', x.p_03, 'ofpk_03', x.ofpk_03)
) ca(Type1, Value1, Type2, Value2);
SQL 小提琴
這篇關(guān)于SQL server 使用 unpivot 函數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!