我有一张包含以下数据的表格:
col-1 col-2 col-3 col-4 col-5 col-6 col-7
----- ----- ----- ----- ----- ----- -----
10 2 30 13 A 0.1 0.3
10 2 30 13 B 0.2 0.9
10 2 30 13 C 0.8 0.7
10 2 30 13 D 0.4 0.5
2 1 8 11 A 0.3 0.4
2 1 8 11 B 0.9 0.2
2 1 8 11 C 0.1 0.8
2 1 8 11 D 0.2 0.5
我必须提出下表:(此处col-1至col-4具有4个不同col-5值的相同值)
col-1 col-2 col-3 col-4 A_6 B_6 C_6 D_6 A_7 B_7
----- ----- ----- ----- --- --- --- --- --- ---
10 2 30 13 0.1 0.2 0.8 0.4 0.3 0.9
2 1 8 11 0.3 0.9 0.1 0.2 0.4 0.2
知道如何实现这个目标吗?
考虑 A_6,因为A_COL_6表示A的Col_6值
答案 0 :(得分:3)
WITH
temp_t
AS
(SELECT '10' col_1,
'2' col_2,
'30' col_3,
'13' col_4,
'A' col_5,
0.1 col_6,
0.3 col_7
FROM DUAL
UNION ALL
SELECT '10', '2', '30', '13', 'B', 0.2, 0.9 FROM DUAL
UNION ALL
SELECT '10', '2', '30', '13', 'C', 0.8, 0.7 FROM DUAL
UNION ALL
SELECT '10', '2', '30', '13', 'D', 0.4, 0.5 FROM DUAL
UNION ALL
SELECT '2', '1', '8', '11', 'A', 0.3, 0.4 FROM DUAL
UNION ALL
SELECT '2', '1', '8', '11', 'B', 0.9, 0.2 FROM DUAL
UNION ALL
SELECT '2', '1', '8', '11', 'C', 0.1, 0.8 FROM DUAL
UNION ALL
SELECT '2', '1', '8', '11', 'D', 0.2, 0.5 FROM DUAL)
SELECT *
FROM temp_t
PIVOT (SUM (col_6) AS c6, SUM (col_7) AS c7
FOR (col_5)
IN ('A', 'B', 'C', 'D'))
答案 1 :(得分:2)
您可以将CASE WHEN
表达式与聚合函数
WITH T AS(
SELECT '10' col_1,'2' col_2,'30' col_3,'13' col_4,'A' col_5, '0.1' col_6,'0.3' col_7 FROM DUAL
UNION ALL
SELECT '10', '2', '30', '13', 'B', '0.2','0.9' FROM DUAL
UNION ALL
SELECT '10', '2', '30', '13', 'C', '0.8','0.7' FROM DUAL
UNION ALL
SELECT '10', '2', '30', '13', 'D', '0.4','.5' FROM DUAL
UNION ALL
SELECT '2' ,'1' ,'8' ,'11','A' , '0.3','0.4' FROM DUAL
UNION ALL
SELECT '2', '1', '8', '11', 'B', '0.9','0.2' FROM DUAL
UNION ALL
SELECT '2', '1', '8', '11', 'C', '0.1','0.8' FROM DUAL
UNION ALL
SELECT '2', '1', '8', '11', 'D', '0.2','0.5' FROM DUAL
)
SELECT COL_1,
COL_2,
COL_3,
COL_4,
MAX(CASE WHEN COL_5 = 'A' THEN COL_6 ELSE '0' END) A_6,
MAX(CASE WHEN COL_5 = 'B' THEN COL_6 ELSE '0' END) B_6,
MAX(CASE WHEN COL_5 = 'C' THEN COL_6 ELSE '0' END) C_6,
MAX(CASE WHEN COL_5 = 'D' THEN COL_6 ELSE '0' END) D_6,
MAX(CASE WHEN COL_5 = 'A' THEN COL_7 ELSE '0' END) A_7,
MAX(CASE WHEN COL_5 = 'B' THEN COL_7 ELSE '0' END) B_7
FROM T
GROUP BY
COL_1,
COL_2,
COL_3,
COL_4
SQLFIDDLE:http://sqlfiddle.com/#!4/b9bb1/21