Oracle 如何根据其他值选择值
我有一个数据表,如下所示Oracle 如何根据其他值选择值,oracle,Oracle,我有一个数据表,如下所示 no s d 100 I D 100 C D 101 C null 101 I null 102 C D 102 I null 100 C D 101 I NULL 102 I NULL 然后我使用这个查询来进行分区 create table pinky nologging as select no,status,dead from(select no,status,dead, row_number() over(partit
no s d
100 I D
100 C D
101 C null
101 I null
102 C D
102 I null
100 C D
101 I NULL
102 I NULL
然后我使用这个查询来进行分区
create table pinky nologging as
select no,status,dead
from(select no,status,dead,
row_number() over(partition by no order by dead desc) seq
from PINK) d
where seq = 1;
我得到了这个结果
100 I D
101 C null
102 I null
但我需要如下所示的数据
no s d
100 I D
100 C D
101 C null
101 I null
102 C D
102 I null
100 C D
101 I NULL
102 I NULL
i、 e
假设每个
no
只能有一条dead为null
记录:
with
-- you data, remove it when running the query
-- in your environment ...
pink (no, status, dead) as
(select 100, 'I', 'D' from dual union
select 100, 'C', 'D' from dual union
select 101, 'C', null from dual union
select 101, 'I', null from dual union
select 102, 'C', 'D' from dual union
select 102, 'I', null from dual
),
-- ... end of you data
--
temp as ( -- a temporary table (CTE) where we make some
-- preliminary calculations
select pink.*,
-- count rows with status = 'I' for this no
sum(case when status = 'I' then 1 else 0 end) over(partition by no) ni,
-- count rows with status = 'C' for this no
sum(case when status = 'C' then 1 else 0 end) over(partition by no) nc,
-- count rows with dead = 'D' for this no
sum(case when dead = 'D' then 1 else 0 end) over(partition by no) nd,
-- total number of rows (in case it's not always = 2)
count(*) over(partition by no) n
from pink
)
select no, status, dead
from temp
where -- pick 'C' if there's also 'I' and all dead = 'D'
status = 'C' and ni > 0 and nd = n
-- pick 'I' if there's also 'C' and all dead is null
or status = 'I' and nc > 0 and nd = 0
-- pick dead is null if there are I's and C's and
-- all other dead's = 'D'
or dead is null and ni > 0 and nc > 0 and n - nd = 1;
是否总是有成对的记录,每个记录都
否?或者可以有两个以上的记录,其中有一些没有?