Reputation: 151
I have two tables, one is a product transforming history table and the other is the products table:
dbo.Product_Change_History
Date FK_ProductID FK_FinalProductID ChangedBy
20160709 1 3 John
dbo.Product_Detail
PK_ProductID ProductName
1 Red Bike
3 Green Bike
I would like a table like:
Date ProductName FinalProductName
20160709 Red Bike Green Bike
How do I join the two tables to achieve this? edit: This is in TSQL
Upvotes: 4
Views: 4033
Reputation: 151
Thank you for the responses, with the help Chad Zinks answer I came to the correct solution:
select
PRDHIST.Date,
OLDPROD.ProductName,
NEWPROD.ProductName
from dbo.Product_ChangeHistory PRDHIST
inner join dbo.Product_Detail OLDPROD
on OLDPROD.PK_ProductID = PRDHIST.FK_ProductID
inner join dbo.Product_Detail NEWPROD
on NEWPROD.PK_ProductID = PRDHIST.FK_FinalProductID;
Upvotes: 0
Reputation: 7063
declare @ProdChange table(ProductID int, FK_ProductID INT, FK_FinalProductID INT, ChangedBy Varchar(100))
declare @Prod table(ProductID int, ProductName Varchar(100))
insert into @Prod Values(1,'Red Bike')
insert into @Prod Values(3,'Green Bike')
insert into @ProdChange Values(1,1,3,'John')
select * from @Prod
select * from @ProdChange
SELECT
old.ProductName,
new.ProductName as FinalProductName
FROM
@Prod as old
INNER JOIN @ProdChange as link
ON old.ProductID = link.FK_ProductID
INNER JOIN @Prod as new
ON new.ProductID = link.FK_FinalProductID
Upvotes: 0
Reputation: 11
I'm not sure about LEFT joins VS INNER. I would think this would work well.
SELECT
link.Date,
old.ProductName,
new.ProductName as FinalProductName
FROM
dbo.Product_Detail as old
INNER JOIN dbo.Product_Change_History as link
ON old.PK_ProductID = link.FK_ProductID
INNER JOIN dbo.Product_Detail as new
ON new.PK_ProductID = link.FK_FinalProductID
Upvotes: 1
Reputation: 360572
You'd have to join twice, which means you to alias at least one of the joins:
SELECT Date, foo.ProductName, bar.FinalProductName
FROM Product_Change_history
LEFT JOIN Product_Detail AS foo ON fk_productid = foo.pk_productid
LEFT JOIN Product_Detail AS bar ON fk_finalproductid = bar.pk_productid
Upvotes: 6