仅在具有NULL的连续记录中替换重复值

时间:2015-11-23 05:25:17

标签: sql oracle

说我有两张桌子 Tran(Tran_Id,Tran_Name) TFlag(Tran_Id,Flag)

我的查询结果如下:

TRAN_ID TRAN_NAME   FLAG    
-------------------------
101     Lend        A   
101     Lend        B   
101     Lend        C   
101     Lend        D   
102     Borrow      E   
101     Lend        F   
101     Lend        G   

我希望输出如下:

TRAN_ID TRAN_NAME   FLAG
-------------------------
101     Lend        A   
(null)  (null)      B   
(null)  (null)      C   
(null)  (null)      D   
102     Borrow      E   
101     Lend        F   
(null)  (null)      G   

2 个答案:

答案 0 :(得分:4)

您可以使用分析 LAG()OVER()

SQL Fiddle 用于演示。

例如,

SQL> SELECT
  2    CASE
  3      WHEN lag(tran_id) over(order by NULL) = tran_id
  4      THEN NULL
  5      ELSE tran_id
  6    END tran_id,
  7    CASE
  8      WHEN lag(tran_name) over(order by NULL) = tran_name
  9      THEN NULL
 10      ELSE tran_name
 11    END tran_name,
 12    flag
 13  FROM t;

   TRAN_ID TRAN_N F
---------- ------ -
       101 Lend   A
                  B
                  C
                  D
       102 Borrow E
       101 Lend   F
                  G

7 rows selected.

答案 1 :(得分:1)

在SQL Server和Oracle中,您都可以使用LAG分析功能。甲骨文:

WITH data (tran_id, tran_name, flag) AS (
    SELECT  01,   'Lend', 'A' FROM DUAL UNION ALL
    SELECT 101,   'Lend', 'B' FROM DUAL UNION ALL
    SELECT 101,   'Lend', 'C' FROM DUAL UNION ALL
    SELECT 101,   'Lend', 'D' FROM DUAL UNION ALL
    SELECT 102, 'Borrow', 'E' FROM DUAL UNION ALL
    SELECT 101,   'Lend', 'F' FROM DUAL UNION ALL
    SELECT 101,   'Lend', 'G' FROM DUAL 
)
SELECT
    NVL2(keep, tran_id, null) tran_id,
    NVL2(keep, tran_name, null) tran_name,
    flag
FROM (
    SELECT
        tran_id, tran_name, flag,
        CASE WHEN LAG(tran_id) OVER (ORDER BY flag) <> tran_id OR LAG(tran_name) OVER (ORDER BY flag) <> tran_name THEN 1 END keep
    FROM
        data)