Checking distinct values on column level

时间:2019-04-08 13:39:32

标签: sql sql-server tsql sql-server-2008

I have four columns coming from my query. My requirement is to check if the values of all the columns are different then only select the result.

I have written this query and it is working fine. But I was just wondering if there is any better or shortcut way to achieve this

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))

1 个答案:

答案 0 :(得分:1)

嗯。 。 。您似乎希望这四个值不同或Name 3。另一种方法使用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; 值,然后检查其余所有值是否均不同。

相关问题