使用oracle SQL,在下面的数据集中,我想检查列B ='N'时,我希望它在列A中找到相同的ID,并比较列C中的行对于该ID。如果它们是相同的那么'Y',如果不是那么'N'否则为空。
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 :(得分:0)
正如其他注释所述,根据您声明的规则,最后一行应该在B中具有值“N”。以下脚本根据规定的规则返回正确的结果,但与您的示例输出不匹配:< / p>
/* 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 |
|-----+------|