2017-07-19 109 views
0

使用oracle SQL,在下面的數據集中,我想要檢查列B ='N'時,我希望它在列A中找到相同的ID並比較列C中的行是爲那個ID。如果它們相同,那麼'Y',如果不是那麼'N'否則爲空。Oracle SQL - 比較列

A B C  D 
001 Y Pizza Pepperoni 
002 Y Pizza Pepperoni 
003 Y Pizza Pepperoni 
003 N Pizza Sausage 
004 Y Pizza Pepperoni 
005 Y Pizza Pepperoni 
005 N Pizza Sausage 
005 N Hamburger Cheese 

理想情況下,我會運行它返回的ID(列A)和case語句,使得它看起來像這樣的結果...

A  B 
001 (Null) 
002 (Null) 
003 (Null) 
003 Y 
004 (Null) 
005 (Null) 
005 Y 
005 N 

誰能給我提供什麼碼你會用它來完成這個?

+0

你能正確格式化你的例子嗎? – fhossfel

+0

我改進了格式。有人必須進行同行評審並接受它。 –

+0

爲什麼倒數第二是Y輸出。它應該是N,因爲對於ID 005,有值比薩餅和漢堡包 –

回答

0

由於其他註釋狀態,根據規定的規則,倒數第二行在B中應該有一個值'N'。以下腳本根據規定的規則返回正確的結果,但與您的示例輸出不匹配:

/* test data */ 
select '001' as a, 'Y' as b, 'Pizza' as c,  'Pepperoni' as d into testtable union all 
select '002' as a, 'Y' as b, 'Pizza' as c,  'Pepperoni' as d union all 
select '003' as a, 'Y' as b, 'Pizza' as c,  'Pepperoni' as d union all 
select '003' as a, 'N' as b, 'Pizza' as c,  'Sausage' as d union all 
select '004' as a, 'Y' as b, 'Pizza' as c,  'Pepperoni' as d union all 
select '005' as a, 'Y' as b, 'Pizza' as c,  'Pepperoni' as d union all 
select '005' as a, 'N' as b, 'Pizza' as c,  'Sausage' as d union all 
select '005' as a, 'N' as b, 'Hamburger' as c, 'Cheese' as d 
go 

/* script */ 
select 
    a 
    ,case when b = 'Y' then null else 
    case when c = lag(c, 1) over (partition by a order by c desc, d) then 'Y' else 'N' end 
    end as b 

from testtable 
go 


/* Results...*/ 

|-----+------| 
| A | B | 
|-----+------| 
| 001 | NULL | 
| 002 | NULL | 
| 003 | NULL | 
| 003 | Y | 
| 004 | NULL | 
| 005 | NULL | 
| 005 | Y | 
| 005 | N | 
|-----+------| 
+0

我感謝你的幫助。但是,我不知道我是否正確解釋。第二行到最後一行的結果應該是'Y',因爲它在列c中具有相同的值。我應該在我的例子中簡單地排除列D,因爲它並不重要。 – dbwhite64

+0

好的,試試新的腳本。 –