如何从SQL Server中的表的所有列获取不同的值

时间:2012-11-08 08:21:47

标签: sql sql-server select distinct

我想用它的ID检索不同值的记录,Table就像这样::

ID     Name
1      Soap
2      eridu
3      Soap
4      rewfig
5      Soap

现在我想要结果:

ID  Name
1   Soap
2   eridu
3   rewfig

我这样使用:[表名是tblRecord

select Distinct(Name) ,ID
  from tblRecord
 where Name in (select Distinct(Name) 
                  from tblRecord
               )

2 个答案:

答案 0 :(得分:3)

SELECT ID, Name
FROM 
(
    SELECT ID, Name,
            ROW_NUMBER() OVER  (PARTITION BY NAME ORDER BY ID ASC) rn
    FROM tableName
) s
WHERE rn = 1
ORDER BY ID

但如果您没有其他列,最简单的解决方案是

SELECT MIN(ID) ID, Name
FROM tableName
GROUP BY Name

答案 1 :(得分:2)

试试这个:

;WITH CTE AS
(
  SELECT Id, Name, ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Id) row_num
  FROM Table
)
SELECT Id, Name
FROM CTE
WHERE row_num = 1;

这会给你:

ID  NAME
2   eridu
4   rewfig
1   Soap

如果您想获得与您在问题中所做的完全相同的输出。您需要为结果生成新的排名编号。尝试使用DENSE_RANK()函数,如下所示:

;WITH CTE AS
(
  SELECT Id, Name, ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Name) row_num
  FROM Table1
)
SELECT DENSE_RANK() OVER(ORDER BY Name) ID, Name
FROM CTE
WHERE row_num = 1;

这应该可以为您提供准确的结果集:

ID  NAME
1   eridu
2   rewfig
3   Soap

SQL Fiddle Demo