Sunday, January 5, 2014

SQL - Select Distinct for Only One Column

PARTITION is used to select distinct value from only one column.
For example,
 
SELECT ID, ProductModel, ProductName FROM Products
where I want non-duplicate values of productName.

This code does the above problem

 
SELECT *
FROM (
    SELECT  ID, ProductName, ProductModel,
            ROW_NUMBER() OVER(PARTITION BY ProductName ORDER BY ID DESC) rn
    FROM Products
) a
WHERE rn = 1

No comments:

Post a Comment