首页 > 解决方案 > 在 Oracle SQL 中选择唯一行并忽略空值

问题描述

有一个包含四列的表:客户、城市、邮政编码和街道。对于每个客户,我想计算唯一地址的数量。不幸的是,某些列中可能存在空值:城市、邮政编码或街道。在比较不同的计数时,我必须忽略它们。所以这不能通过简单的 group by 和 count distinct 来解决。

例如,有

'client1', 'city1', 'postcode1', 'street1'
'client1', 'city1', 'postcode1', null
'client1', 'city1', null, 'street1'
'client1', null, null, 'street2'

'client1', 'city2', null, 'street1'
'client1', 'city2', null, 'street2'

对于我的任务,唯一地址应该是(已编辑

'client1', 'city1', 'postcode1', 'street1'

'client1', 'city2', null, 'street1'
'client1', 'city2', null, 'street2'

(所以答案是 client1 的 3 个唯一地址),
但对于标准的 distinct 子句,这些都是唯一的,例如,行

'client1', 'city1', 'postcode1', 'street1'
'client1', 'city1', 'postcode1', null
'client1', 'city1', null, 'street1'

被视为不同,而对于我的任务,这些并没有什么不同,我想将它们计为 1。

在一些评论后编辑: 如果我们有

'client1', null, null, 'street3'

那么这是一个唯一的地址(因为没有其他带有“street3”的地址)并且应该被计算在内。

标签: sqloracle

解决方案


您可以min按如下方式使用分析功能:

Select distinct t.client,
       t.city,
       Coalesce(t.postcode,Min(t.postcode) over (partition by t.client, t.city)) as postcode,
       Coalesce(t.street,Min(t.street) over (partition by t.client, t.city)) as street
  From your table
 Where city is not null;

--更新

我可以想到自我解决方案,检查它是否适合您。

Select distinct a.client,
       Coalesce(a.city, b.city) as city,
       Coalesce(a.postcode, b.postcode) as postcode,
       Coalesce(a.street, b.street) as street
  From your_table a left join your_table b
    On a.client = b.client
   And (a.city = b.city or (a.city is null or b.city is null))
   And (a.postcode = b.postcode or (a.postcode is null or b.postcode is null))
   And (a.street = b.street or (a.street is null or b.street is null))
   And a.rowid <> b.rowid
       

推荐阅读