我有一个问题,可以通过轴心解决,但无法解决。请帮我做到这一点。
表格
CREATE TABLE table_name ( CUST_ID, RATE ) AS
SELECT 1, 100 FROM DUAL UNION ALL
SELECT 1, 200 FROM DUAL UNION ALL
SELECT 2, 100 FROM DUAL UNION ALL
SELECT 3, 300 FROM DUAL UNION ALL
SELECT 4, 200 FROM DUAL UNION ALL
SELECT 4, 600 FROM DUAL UNION ALL
SELECT 5, 500 FROM DUAL UNION ALL
SELECT 6, 800 FROM DUAL UNION ALL
SELECT 6, 200 FROM DUAL;
必需的输出
CUST_ID RATE CUST_ID RATE CUST_ID RATE CUST_ID RATE CUST_ID RATE CUST_ID RATE
------- ---- ------- ---- ------- ---- ------- ---- ------- ---- ------- ----
1 100 2 100 3 300 4 200 5 500 6 800
1 200 4 600 6 200
请帮助我解决它。
答案 0 :(得分:0)
Oracle查询:
SELECT "1_CUST_ID" AS CUST_ID1,
"1_RATE" AS RATE1,
"2_CUST_ID" AS CUST_ID2,
"2_RATE" AS RATE2,
"3_CUST_ID" AS CUST_ID3,
"3_RATE" AS RATE3,
"4_CUST_ID" AS CUST_ID4,
"4_RATE" AS RATE4,
"5_CUST_ID" AS CUST_ID5,
"5_RATE" AS RATE5,
"6_CUST_ID" AS CUST_ID6,
"6_RATE" AS RATE6
FROM (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY cust_id ORDER BY ROWNUM ) AS rn
FROM table_name t
)
PIVOT (
MAX( cust_id ) AS cust_id,
MAX( rate ) AS rate
FOR cust_id IN ( 1, 2, 3, 4, 5, 6 )
)
输出:
CUST_ID1 RATE1 CUST_ID2 RATE2 CUST_ID3 RATE3 CUST_ID4 RATE4 CUST_ID5 RATE5 CUST_ID6 RATE6
-------- ----- -------- ----- -------- ----- -------- ----- -------- ----- -------- -----
1 100 2 100 3 300 4 200 5 500 6 800
1 200 4 600 6 200
(注意:您无法按客户ID对行进行排序,并且不能保证查询的顺序是确定的,因此,例如,如果您拥有表格上启用了行移动。)