我有一个无法更改的下表结构。
我正在尝试加入这些表,并希望避免重复记录。
select p.ProductId,p.ProductName,inv.Details from Products p
inner join Inventory inv on(p.ProductId = inv.ProductId)
这里是SqlFiddle。
答案 0 :(得分:4)
从sqlserver 2008+开始,您可以使用交叉申请。
使用交叉应用,您可以在子选择内部进行连接,如此处所示。使用前1名,您可以从表库存中获得最多1行。也可以通过'添加'顺序。对子选择的陈述。但是,这似乎超出了您的问题的范围。
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
答案 1 :(得分:1)
您可以使用row_number函数删除重复项
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
答案 2 :(得分:0)
select p.ProductId,p.ProductName
,(select top 1 inv.Details from Inventory inv where (p.ProductId = inv.ProductId))Details
from Products p
或
select * from
(
select p.ProductId,p.ProductName,inv.Details
,ROW_NUMBER()over(partition by p.productid order by p.productid)rn from Products p
inner join Inventory inv on(p.ProductId = inv.ProductId)
)t4
where rn=1
答案 3 :(得分:0)
with cte as
(select p.ProductId,p.ProductName,inv.Details,
RoW_Number() OVER(Partition by p.ProductId,p.ProductName,inv.Details
Order by p.ProductId,p.ProductName,inv.Details) rn
from Products p
inner join Inventory inv on(p.ProductId = inv.ProductId))
select ProductId,ProductName,Details from cte where rn = 1