在SQL或oracle

时间:2017-07-17 13:57:23

标签: sql oracle

我有一个以下列格式给出的数据集 帐户类

enter image description here

我需要在Oracle中以下列格式转换它 enter image description here

我怎么能做这个庞大的数据集

1 个答案:

答案 0 :(得分:0)

您可以使用PIVOT条款。 但是您需要在课程中为每个帐户分配它的列名。 您可以使用row_number,rank或dense_rank。

WITH tab AS
(SELECT 'A1' ACCOUNT, 'C1' CLASS FROM dual UNION ALL
SELECT 'A2' ACCOUNT, 'C2' CLASS FROM dual UNION ALL
SELECT 'A3' ACCOUNT, 'C1' CLASS FROM dual UNION ALL
SELECT 'A4' ACCOUNT, 'C3' CLASS FROM dual UNION ALL
SELECT 'A5' ACCOUNT, 'C3' CLASS FROM dual UNION ALL
SELECT 'A6' ACCOUNT, 'C2' CLASS FROM dual UNION ALL
SELECT 'A7' ACCOUNT, 'C1' CLASS FROM dual UNION ALL
SELECT 'A8' ACCOUNT, 'C4' CLASS FROM dual UNION ALL
SELECT 'A9' ACCOUNT, 'C5' CLASS FROM dual UNION ALL
SELECT 'A10' ACCOUNT, 'C1' CLASS FROM dual UNION ALL
SELECT 'A11' ACCOUNT, 'C2' CLASS FROM dual UNION ALL
SELECT 'A12' ACCOUNT, 'C1' CLASS FROM dual UNION ALL
SELECT 'A13' ACCOUNT, 'C3' CLASS FROM dual UNION ALL
SELECT 'A14' ACCOUNT, 'C3' CLASS FROM dual UNION ALL
SELECT 'A15' ACCOUNT, 'C2' CLASS FROM dual UNION ALL
SELECT 'A16' ACCOUNT, 'C1' CLASS FROM dual UNION ALL
SELECT 'A17' ACCOUNT, 'C1' CLASS FROM dual )
SELECT *
  FROM (SELECT CLASS,
               ACCOUNT,
               row_number() OVER (PARTITION BY class ORDER BY account) col_num
          FROM tab)
 PIVOT (MAX(account) FOR col_num IN (1,2,3,4,5,6,7,8))

此示例按字母顺序对帐户进行排序(A1,A10,A12,A16,A3,A7,...)。 如果需要其他排序,在row_number函数的ORDER BY子句中实现也不难。