Using oracle SQL, in the data set below, I want to examine when column B = 'N', I want it to find the same ID in column A and compare what the rows in column C are for that ID. if they are the same then 'Y', if not then 'N' else null.
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
Ideally, I would run it to return the ID (column A) and the results of the case statement such that it looks like this...
A B
001 (Null)
002 (Null)
003 (Null)
003 Y
004 (Null)
005 (Null)
005 Y
005 N
Can anyone provide me what code you would use to accomplish this?
As the other comments state, given your stated rules the second last row should have a value 'N' in B. The following script returns the correct result according to the stated rules, but doesn't match your sample output:
/* 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 |
|-----+------|
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.