Sql-server – Select Distinct for Multiple columns

sql server

SELECT top 50 column1, column2,column3,column4
FROM (Select Distinct column1,column2, column3, column4 from Table
Where Column2>= '2016-07-01' )
Order By Column2;

The result is not what I am expecting. I want to make columns Column1, Column2, Column3, Column4 all distinct, meaning each column should have no two identical values. Is there a way to do this?

Best Answer

I don't think it is possible to get your expected result set using a single Select-statement. IMHO you must create an empty copy of the result table and then use following single-row Insert to prevent any duplicate values. Repeat this until you get the expected n rows.

insert into result_table
select top 1 column1, column2,column3,column4
from base_table as t1
where Column2>= '2016-07-01'
  and not exists 
  ( select * 
    from result_table as t2
     where Column2>= '2016-07-01'
       and
        (  t1.column1 = t2.column1 -- unique data in each column
        or t1.column2 = t2.column2
        or t1.column3 = t2.column3
        or t1.column4 = t2.column4
        )
  )
 Order By Column2;