Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql remove duplicate record while using join

Tags:

sql

sql-server

I have a following table structure which can't be change.

enter image description here

I'm trying to join these table and want to avoid duplicate records as well.

 select p.ProductId,p.ProductName,inv.Details from Products p
inner join Inventory inv on(p.ProductId = inv.ProductId)

here is SqlFiddle.

like image 230
Ashwini Verma Avatar asked Sep 24 '26 03:09

Ashwini Verma


2 Answers

From sqlserver 2008+ you can use cross apply.

With cross apply you can make a join inside the subselect as demonstrated here. With top 1 you get maximum 1 row from table Inventory. It will also be possible to add an 'order by' statement to the subselect. However that seems out of scope for your question.

select p.ProductId,p.ProductName,x.Details 
from Products p
cross apply
(SELECT top 1 inv.Details FROM Inventory inv WHERE p.ProductId = inv.ProductId) x
like image 191
t-clausen.dk Avatar answered Sep 26 '26 18:09

t-clausen.dk


You can use row_number function to remove duplicates

   WITH New_Inventory AS
    (
        SELECT Productid, Details,
        ROW_NUMBER() OVER (Partition by Productid ORDER BY details) AS RowNumber
        FROM Products
    ) 
    select p.ProductId,p.ProductName,inv.Details from Products p
    inner join New_Inventory inv on(p.ProductId = inv.ProductId)
    where RowNumber = 1
like image 20
rogue-one Avatar answered Sep 26 '26 17:09

rogue-one



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!