2015-11-23 107 views
-1

說我有兩個表
陳德良(Tran_Id,Tran_Name) TFlag(Tran_Id,旗)只有在連續的記錄用NULL替換重複值

我的查詢結果一樣:

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 
+1

你有什麼迄今所做?和請選擇只有一個RDBMS,其無論是SQL Server或Oracle。 – brenners1302

+0

在Oracle中。我知道要將所有重複項都替換爲null。但不適用於'連續記錄'。 –

回答

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) 
+0

其工作正常。謝謝你。但我還有一個場景。 –

+0

IF 我的查詢結果包含字段(domain_name,plan_name,Tran_id,Tranname,標誌) for每個domain_name計劃名是通過加入域和計劃表獲得的,tran_id通過加入計劃和轉換表,標記通過加入tran和Tflag表獲得。 .. 這裏Domain_name和Plan_name只能連續複製。作爲tran_id,tran_name,標誌有重複如表..(它可能會在以後重複) 現在我想要與上述相同的輸出,但按(域名,計劃名,交易名) –

3

你可以使用分析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.