T-SQL 如何从一列中选择没有重复值的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3682956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
T-SQL How to select rows without duplicate values from one column?
提问by Tony
I have a table with 2 columns ID, ID_PROJ_CSR
我有一个有 2 列的表格 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 747OR 786
我想选择 ID,但如果 ID_PROJ_CSR 中的任何值是重复的,我需要选择包含该重复值的行的任何 ID(在该示例中,选择 ID 747OR 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)
回答by cjk
You need to GROUP BY:
您需要 GROUP BY:
SELECT MAX(ID) as [ID], ID_PROJ_CSR
FROM my_table
GROUP BY ID_PROJ_CSR
回答by Gregory Kaczmarczyk
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;