使用 with 子句消除具有空值的重复行

Eliminating duplicate rows with null values using with clause

我们如何通过使用 with 子句语句仅选择在特定字段中具有值的那些来消除重复项?

查询是这样的:

with x as (--queries with multiple join tables, etc.)
select distinct * from x

输出如下:

Com_no   Company      Loc    Rewards
1         Mccin      India      50
1         Mccin      India
2         Rowle      China      18
3         Draxel     China      11
3         Draxel     China  
4         Robo       UK          

如您所见,我得到了重复的记录。我想摆脱不唯一的空值。也就是说,Robo 是唯一的,因为它在 Rewards 中只有 1 条记录为空值,所以我想保留它。

我试过这个:

 with x as (--queries with multiple join tables, etc.)
 select distinct * from x where Rewards is not null

当然这是不对的,因为它也摆脱了 4 Robo UK

预期输出应为:

1         Mccin      India      50
2         Rowle      China      18
3         Draxel     China      11 
4         Robo       UK      

问题是您将这些行称为重复项,但它们不是重复项。他们是不同的。因此,您要做的是排除 Rewards 为空的行,除非没有任何具有非空值的行,然后 select 不同的行。所以像:

select distinct * 
from x a
where Rewards is not null 
or (Rewards is null and not exists (select 1 from x b where a.Com_no = b.Com_no 
    and b.Rewards is not null)

现在您的 Robo 行仍将被包括在内,因为在 x 中没有一行 Rewards 不为 null 的 Robo,但是具有 null Rewards 的其他公司的行将被排除,因为没有空行他们。

这是一个优先查询。一种方法是使用 row_number()。如果每个 Com_no/Company/Loc 只需要一个值,那么:

select x.*
from (select x.*,
             row_number() over (partition by Com_no, Company, Loc order by Rewards nulls last) as seqnum
      from x
     ) x
where seqnum = 1;

甚至:

select Com_no, Company, Loc, max(Rewards)
from x
group by Com_no, Company, Loc;