我有下表
SpareParts | JPY | INR | SGD | IDR |
sp1 1 25 75 200
sp2 4 33 35 400
sp3 5 44 77 200
我想要像BELOW一样放弃
SpareParts | currency | value
sp1 JPY 1
sp1 INR 25
SP1 SGD 74
SP1 IDR 200
sp2 JPY 4
sp2 INR 33
SP2 SGD 35
SP2 IDR 400
sp3 JPY 5
sp3 INR 44
SP3 SGD 77
SP3 IDR 200
请帮我解决这个问题。
答案 0 :(得分:1)
您尝试的操作通常称为UNPIVOT
。虽然SQL Server提供UNPIVOT
作为操作,但我发现以下模式通常更有效;
;WITH SpareParts (SpareParts, JPY, INR,SGD, IDR) AS
(
SELECT 'sp1', 1, 25, 75, 200 UNION ALL
SELECT 'sp2', 4, 33, 35, 400 UNION ALL
SELECT 'sp3', 5, 44, 77, 200
)
SELECT SP.SpareParts
,CA.*
FROM SpareParts SP
CROSS
APPLY (
SELECT 'JPY', JPY UNION ALL
SELECT 'INR', INR UNION ALL
SELECT 'SGD', SGD UNION ALL
SELECT 'IDR', IDR
) CA (Currency, [Value])
答案 1 :(得分:1)
以下是使用UNPIVOT
对您的数据进行格式化的示例:
-- create a temp table with your sample data
SELECT * INTO #temp
FROM
(SELECT 'sp1' as spareParts, 1 as JPY, 25 as INR, 75 as SGD, 200 as IDR
UNION
SELECT 'sp2' as spareParts, 4 as JPY, 33 as INR, 35 as SGD, 400 as IDR
UNION
SELECT 'sp3' as spareParts, 5 as JPY, 44 as INR, 75 as SGD, 200 as IDR) as t
-- output the sample data in current format
SELECT * FROM #temp
-- preform the unpivot and show reformatted data
SELECT SpareParts, Currency, Value
FROM
(SELECT SpareParts, JPY, INR, SGD, IDR
FROM #temp) t
UNPIVOT
(Value FOR Currency IN
(JPY, INR, SGD, IDR)
)AS unpvt
您可以在管理工作室的新查询窗口中运行它,看它是否正常工作。
答案 2 :(得分:0)
您也可以使用交叉连接来实现相同的
Select SpareParts
,CASE Value
WHEN 'JPY' THEN JPY
WHEN 'INR' THEN INR
WHEN 'SGD' THEN SGD
WHEN 'IDR' THEN IDR
END AS Currency
,Value
from Currency
Cross JOIN (VALUES ('JPY'),('INR'),('SGD'),('IDR')) AS CC(Value)