Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL How to select rows without duplicate values from one column?

I have a table with 2 columns ID, ID_PROJ_CSR

The content of that table is:

ID     ID_PROJ_CSR
------------------
747    222   <
785    102
786    222   <
787    223
788    224

I want to select the ID, but if any value from ID_PROJ_CSR is a duplicate, I need to select any ID of the rows that contains that duplicate value (in that example, select ID 747 OR 786

I try:

SELECT * FROM my_table tab 
WHERE tab.id_proj_csr = (SELECT TOP 1 id_proj_csr
                         FROM my_table mt
                         WHERE mt.id_proj_csr = tab.id_proj_csr)
like image 403
Tony Avatar asked Sep 10 '10 07:09

Tony


2 Answers

You need to GROUP BY:

SELECT MAX(ID) as [ID], ID_PROJ_CSR
FROM my_table
GROUP BY ID_PROJ_CSR
like image 155
cjk Avatar answered Oct 13 '22 00:10

cjk


Here's the case of omitting anything that has a duplicate value, so you'll only get rows that don't have duplicates:

SELECT *
FROM my_table
GROUP BY ID_PROJ_CSR
HAVING count(ID_PROJ_CSR) = 1;
like image 32
Gregory Kaczmarczyk Avatar answered Oct 13 '22 02:10

Gregory Kaczmarczyk