Search code examples
sql-server-2005t-sqldistinct-values

T-SQL Distinct column problem when trying to filter duplicates out


I have the following data

COL-1     COL-2

1        0TY/OK
1        0TY/OK
1        0TY/OK 
1        0TY/OK 
1        0TY/OK
2        2KP/L         
2        2KP/L
2        2KP/L  
2        2KP/L       
2        2KP/L      
3        7U5/2M
3        7U5/2M 
3        7U5/2M 
3        7U5/2M

And i want to construct a select query to retrieve that data in the output below

COL-1     COL-2        COL-3

1        0TY/OK      0TY/OK
1        0TY/OK      2KP/L  
1        0TY/OK      7U5/2M
1        0TY/OK 
1        0TY/OK
2        2KP/L         
2        2KP/L
2        2KP/L  
2        2KP/L       
2        2KP/L      
3        7U5/2M
3        7U5/2M 
3        7U5/2M 
3        7U5/2M

I want COL3 to return the distinct values of COL2

Using SELECT COL1, COL2, DISTINCT COL2 AS COL3 FROM MYTable does not work is SQL SERVER


Solution

  • Although I'm sure that some SQL wizard will be able to construct a way to do this, I feel the need to point out that conceptually this doesn't make sense - the values in the rows of column 3 are completely unrelated to the row values in columns 1 and 2.

    Can you not simply return the distinct values of COL2 in a separate query?

    SELECT DISTINCT COL2 FROM MyTable
    

    (Note that you can return multiple resultsets from a single SQL query)