sql - 在 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”的地址)并且应该被计算在内。
解决方案
您可以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
推荐阅读
- docker - 尝试在 docker 中使用 dep 安装依赖项
- python - 如何根据值更改列表值?
- css - 将 css 箭头附加到 css 边框的顶部
- java - ImageReader.OnImageAvailableListener 在 Android Things 上总是以“缓冲区已被释放”失败的原因可能是什么
- python - Python 递归函数如何用于 tri_recursion 函数?
- google-cloud-platform - GCP 创建随机复制器实例
- html - 如何调整html中的部分?
- javascript - 为输入字段赋值
- php - 在同一域上使用 httpd.conf 访问两个目录
- sony - 索尼STR-DN1080如何从网络中唤醒?