我有两个表,1:n关系
Product (id1, id2, name, CreatedBy)
ProductVersion (id, ProductId1, ProductId2,VersionNumber, description)
( *每个包都有多个版本(按顺序编号) *包有id1和id2,它们将唯一键组合在一起 )
我查询每个产品的最新(顶级)版本如下
SELECT p.id1, p.id2, max(pv.VersionNumber)
FROM Product p
join ProductVersion pv on p.Id1 = pv.ProductId1 and p.Id2 = pv.ProductId2
group by p.Id1, p.id2
现在,
我想要pv.id - 作为顶部返回的版本的id
我该如何获取它?
答案 0 :(得分:1)
您可以这样做,例如:
select p.id1, p.id2, pv.id
from Product as p
outer apply (
select top 1 t.id
from ProductVersion as t
where t.ProductId1 = p.Id1 and t.ProductId2 = p.Id2
order by t.VersionNumber desc
) as pv
或使用row_number()方法:
with cte as (
select
p.id1, p.id2, pv.id,
row_number() over(partition by p.id1, p.id2 order by pv.VersionNumber desc) as rn
from Product as p
left outer join ProductVersion as pv on pv.ProductId1 = p.Id1 and pv.ProductId2 = p.Id2
)
select * from cte where rn = 1
答案 1 :(得分:1)
您可以进一步优化您的加入,仅加入最大版本号:
SELECT p.id
, pv.id AS VersionId
, pv.VersionNumber
FROM Product p
JOIN ProductVersion pv
ON p.Id = pv.ProductId
AND pv.VersionNumber = ( SELECT MAX(VersionNumber)
FROM ProductVersion
WHERE ProductId = p.Id)