在 Oracle 11G 中转置的三个可能选项
要使用数据透视,在您的代码中是不可能的,因为您的初始数据集已经被透视。
WITH TEMP1
AS (SELECT
6657 AS CID,
100 AS VAL,
'X1' AS XCORD,
2014 AS FY
FROM
DUAL
UNION ALL
SELECT
6657 AS CID,
0 AS VAL,
'X2' AS XCORD,
2014 AS FY
FROM
DUAL
UNION ALL
SELECT
6657 AS CID,
0 AS VAL,
'X3' AS XCORD,
2014 AS FY
FROM
DUAL
UNION ALL
SELECT
6657 AS CID,
200 AS VAL,
'X4' AS XCORD,
2014 AS FY
FROM
DUAL
UNION ALL
SELECT
6658 AS CID,
300 AS VAL,
'X1' AS XCORD,
2015 AS FY
FROM
DUAL
UNION ALL
SELECT
6658 AS CID,
0 AS VAL,
'X2' AS XCORD,
2015 AS FY
FROM
DUAL
UNION ALL
SELECT
6658 AS CID,
0 AS VAL,
'X3' AS XCORD,
2015 AS FY
FROM
DUAL
UNION ALL
SELECT
6658 AS CID,
400 AS VAL,
'X4' AS XCORD,
2015 AS FY
FROM
DUAL
UNION ALL
SELECT
6659 AS CID,
500 AS VAL,
'X1' AS XCORD,
2016 AS FY
FROM
DUAL
UNION ALL
SELECT
6659 AS CID,
0 AS VAL,
'X2' AS XCORD,
2016 AS FY
FROM
DUAL
UNION ALL
SELECT
6659 AS CID,
0 AS VAL,
'X3' AS XCORD,
2016 AS FY
FROM
DUAL
UNION ALL
SELECT
6659 AS CID,
600 AS VAL,
'X4' AS XCORD,
2016 AS FY
FROM
DUAL)
SELECT
*
FROM
(SELECT
XCORD,
FY,
SUM ( VAL ) AS VAL
FROM
TEMP1
GROUP BY
XCORD,
FY) PIVOT (SUM ( VAL ) FOR FY IN ('2014', '2015', '2016'))
ORDER BY
XCORD;
结果:
XCORD '2014' '2015' '2016'
----- ------ ------ ------
X1 100 300 500
X2 0 0 0
X3 0 0 0
X4 200 400 600
如果您查看数据集,您可以看到结果是
CID VAL XCORD FY
---- ---- ----- ----
6657 100 X1 2014
6657 0 X2 2014
6657 0 X3 2014
6657 200 X4 2014
6658 300 X1 2015
6658 0 X2 2015
6658 0 X3 2015
6658 400 X4 2015
6659 500 X1 2016
6659 0 X2 2016
6659 0 X3 2016
6659 600 X4 2016
这或多或少是您数据的 UNPIVOT。