Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Omit/Ignore repetitive data from a specific column

For my question lets consider the following sample table data:

ProductID    ProductName    Price   Category

1                Apple                 5.00       Fruits
2                Apple                 5.00       Food
3                Orange               3.00       Fruits
4                Banana                 2.00       Fruits


I need a query which will result in the following data set:

ProductID    ProductName    Price   Category

1                Apple                 5.00       Fruits
3                Orange               3.00       Fruits
4                Banana                 2.00       Fruits


As you can see ProductID 2 has been omitted/ignored because Apple is already present in the result i.e. each product must appear only once irrespective of Category or Price.

Thanks

like image 666
Raihan Iqbal Avatar asked Nov 05 '22 15:11

Raihan Iqbal


1 Answers

SELECT  *
FROM    (
        SELECT  *, ROW_NUMBER() OVER (PARTITION BY productName ORDER BY price) AS rn
        FROM    mytable
        ) q
WHERE   rn = 1
like image 104
Quassnoi Avatar answered Nov 12 '22 17:11

Quassnoi