问题
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
Table structure
create table test(p_01 int,
p_02 int,
p_03 int,
ofpk_01 int,
ofpk_02 int,
ofpk_03 int)
SQL fiddle link
Is this possible with unpivot function? here is what I've got so far:
回答1:
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 Fiddle
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 Fiddle
回答2:
I don't think you can do this with unpivot
. I think you'll have to do something like:
Select
'p_01' type,
p_01 value,
'ofpk_01' type2,
ofpk_01 value2
From
test
Union All
Select
'p_02',
p_02,
'ofpk_02',
ofpk_02
From
test
Union All
Select
'p_03',
p_03,
'ofpk_03',
ofpk_03
From
test
Example Fiddle
来源:https://stackoverflow.com/questions/19208452/sql-server-using-unpivot-function