不考虑NULL值的重复记录计数

时间:2020-01-15 09:31:15

标签: sql sql-server sql-server-2017

样本数据:

target: "{{ input | regex_findall('\\sSSLFile.*') }}"

预期结果: 2

说明:

我需要在上面计算唯一记录,这种情况下的定义是该记录中的所有填充值必须相同,但是如果其中一条记录具有填充值而另一条记录具有NULL,则同一列,则必须将其视为相同。

因此在上面的示例中,计数将为2,因为对于记录1和2,所有填充的列都是相同的,并且列4中的D必须比较等于NULL。 有人对如何执行此操作有任何建议吗?

3 个答案:

答案 0 :(得分:1)

假设您的表具有一个名为id的主键,则可以使用exists和聚合来实现

select count(*) result
from mytable t
where exists (
    select 1 from mytable t1 
    where 
        t1.id <> t.id 
        and t1.column1 = t.column1
        and t1.column2 = t.column2
        and t1.column3 = t.column3
        and (t1.column4 is null or t.column4 is null or t1.column4 = t.column4)
)

Demo on DB Fiddle

| result |
| -----: |
|      2 |

答案 1 :(得分:1)

我在两个不同的表上遇到了同样的问题。 我使用了内部联接并检查table1.col1是否为null,然后使用table2.col1

例如:从表1完整外部联接表2中选择ISNULL(table1.Col1,table2.Col1)......等等

在同一张表的情况下,您可以应用具有不同别名的联接

检查它是否适合您的情况

答案 2 :(得分:1)

我相信这个问题的正确答案是:

select count(*)
from mytable t1
where not exists (select 1
                  from mytable t2 
                  where t2.id < t1.id and
                        (t2.column1 = t1.column1 or t1.column1 is null or t2.column1 is null) and
                        (t2.column2 = t1.column2 or t1.column2 is null or t2.column2 is null) and
                        (t2.column3 = t1.column3 or t1.column3 is null or t2.column3 is null) and
                        (t2.column4 = t1.column4 or t1.column4 is null or t2.column4 is null) 
                 );

Here是db <>小提琴。

相关问题