在数据具有固定价值的情况下,将数据从一行分成多行

时间:2016-06-27 20:54:28

标签: sql oracle

我有两个表(TEST_1和TEST_2)具有相同的结构。

CREATE TABLE MDMETL.TEST_1 
(   
EMPID       NUMBER, 
EMPDATA1    NUMBER,
EMPDATA2    NUMBER,
EMPDATA3    NUMBER,
EMPDATA4    NUMBER,
EMPDATA5    NUMBER,
EMPDATA6    NUMBER,
EMPDATA7    NUMBER,
EMPDATA8    NUMBER,
EMPDATA9    NUMBER,
EMPDATA10   NUMBER,
EMPDATA11   NUMBER,
EMPDATA12   NUMBER,
EMPDATA13   NUMBER
) ;

并且TEST_1中的数据是:

INSERT INTO TEST_1 VALUES (123, 10, 50, 70, 100, 20, 65, 100, 30, 45, 75, 100, 80, 100);

SELECT * FROM TEST_1;

EMPID EMPDATA1 EMPDATA2 EMPDATA3 EMPDATA4 EMPDATA5 EMPDATA6 EMPDATA7 EMPDATA8 EMPDATA9 EMPDATA10 EMPDATA11 EMPDATA12 EMPDATA13
  123       10       50       70      100       20       65      100       30       45        75       100        80       100

TEST2中的数据必须如下:

EMPID EMPDATA1 EMPDATA2 EMPDATA3 EMPDATA4 EMPDATA5 EMPDATA6 EMPDATA7 EMPDATA8 EMPDATA9 EMPDATA10 EMPDATA11 EMPDATA12 EMPDATA13
  123       10       50       70      100
  123       20       65      100
  123       30       45       75      100
  123       80      100

每当字段的值为100时,它必须分成下一行。 有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

<强>查询

INSERT INTO TEST_2
SELECT empid,
       "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"
FROM   (
  SELECT empid,
         grp,
         ROW_NUMBER() OVER ( PARTITION BY empid, grp ORDER BY id ) AS id,
         empdata
  FROM   (
    SELECT empid,
           COUNT( CASE empdata WHEN 100 THEN 1 END )
             OVER ( PARTITION BY empid
                    ORDER BY id
                    ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING ) AS grp,
           id,
           empdata
    FROM   TEST_1
    UNPIVOT ( empdata FOR id IN (
      empdata1  AS  1, empdata2  AS  2, empdata3  AS  3, empdata4  AS  4,
      empdata5  AS  5, empdata6  AS  6, empdata7  AS  7, empdata8  AS  8,
      empdata9  AS  9, empdata10 AS 10, empdata11 AS 11, empdata12 AS 12,
      empdata13 AS 13
    ) )
  )
)
PIVOT ( MAX( empdata ) FOR id IN ( 1,2,3,4,5,6,7,8,9,10,11,12,13 ) );

<强>输出

SELECT * FROM test_2;

     EMPID   EMPDATA1   EMPDATA2   EMPDATA3   EMPDATA4   EMPDATA5   EMPDATA6   EMPDATA7   EMPDATA8   EMPDATA9  EMPDATA10  EMPDATA11  EMPDATA12  EMPDATA13
---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
       123         10         50         70        100                                                                                                    
       123         20         65        100                                                                                                               
       123         30         45         75        100                                                                                                    
       123         80        100