-1

I want to retrieve record for distinct value with it's ID ,Table is like this ::

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

Now I want result:

ID  Name
1   Soap
2   eridu
3   rewfig

I use like this: [Table Name is tblRecord

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

2 回答 2

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

but the simpliest Solution if you have no other column is

SELECT MIN(ID) ID, Name
FROM tableName
GROUP BY Name
于 2012-11-08T08:25:00.697 回答
2

Try this:

;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;

This will give you:

ID  NAME
2   eridu
4   rewfig
1   Soap

If you want to get the exact output like what you did in your question. You will need to generate a new ranking number for the result. Try to use DENSE_RANK() function like so:

;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;

This should give you the exact desired result set:

ID  NAME
1   eridu
2   rewfig
3   Soap

SQL Fiddle Demo

于 2012-11-08T08:24:23.410 回答