SQL - 遍历重复项以创建新的条件列

SQL - Loop through duplicates to make new conditional column

太棒了,我在 Oracle 数据库中有数据,我从中提取了一些看起来像这样的行

ID  TYPE 
1   A
1   B
2   A

我有一个转换为条件列的类型列表,例如(如果 A 那么 Y,如果 B 那么 N),所以它看起来像这样

ID  TYPE COND
1   A    Y
1   B    N
2   A    Y

有没有办法添加另一列,检查特定 ID 的 COND 列中的所有值是否都是 Y?所以最终结果是这样的:

ID  TYPE COND COND2
1   A    Y    N
1   B    N    N
2   A    Y    Y

我知道我可以在 R 中轻松做到这一点,但在此过程中跳过使用其他软件会很棒。

使用解析函数。在这种情况下 min() 做你想做的事:

select t.*,
       min(cond) over (partition by id) as cond2
from t;
drop table x101;
create table x101 (
id intEGER,
typ varchar2(20)
);


insert into x101 values (1, 'A');
insert into x101 values (1, 'B');
insert into x101 values (2, 'A');
insert into x101 values (4, 'A');
insert into x101 values (4, 'C');
insert into x101 values (5, 'A');
insert into x101 values (5, 'T');
commit;

With q1 as (
select id, typ,
       case typ 
          when 'A' then 'Y' 
          when 'B' then 'N' 
          when 'C' then 'Y' 
          else 'NA' 
       end as cond
from x101
order by id, typ
)
select id, typ,
       cond,
       case 
          when count(distinct case when cond != 'Y' then 1 end) over (partition by id) = 0 then 'Y' 
          when count(distinct case when cond != 'Y' then 1 end) over (partition by id) = 1 then 'N' 
          else 'NA' 
       end as cond2
from q1
order by id, typ
;

给予

ID  TYP CODE    CODE2
1   A   Y   N
1   B   N   N
2   A   Y   Y
4   A   Y   Y
4   C   Y   Y
5   A   Y   N
5   T   NA  N