在列级别检查不同的值

Checking distinct values on column level

我的查询有四列。我的要求是检查所有列的值是否不同,然后只有 select 结果。

我已经编写了这个查询,并且运行良好。但我只是想知道是否有更好或更快捷的方法来实现这个

select FO, AFO, CO, ACO from mytable 
where 
(fo<>afo or (fo is null or afo is null))
and 
(fo<>co or (fo is null or co is null))
and 
(fo<>aco or (fo is null or aco is null))
and 
(afo<>co or (afo is null or co is null)) 
and 
(afo<>aco or (afo is null or aco is null))
and 
(co<>aco or (co is null or aco is null))

嗯。 . .您似乎希望这四个值不同或 NULL。另一种方法使用 apply:

select t.*
from mytable t cross apply
     (select count(*)
      from (values (t.afo), (t.fo), (t.co), (t.aco)
           ) v(val)
      where val is not null
      having count(*) = count(distinct val)
     ) x;

这将删除 NULL 个值,然后检查其余值是否完全不同。