我有一个名为Packages的表,其中包含一些数据和一个包含其他信息的相关表。它的设置如下:
Name|Version|Architecture|Date|id
在第二个名为Distribution的表中,我有这个:
repo|id
id的互相引用。我希望能够获得某个分组的最新(按日期排序)。我想按名称,架构和回购进行分组。问题是我似乎无法让正常的最大群体正常工作,因为我必须跨越表格。这就是我到目前为止所拥有的
select
p1.Name,
p1.Version,
p1.Arch,
d1.repo,
p1.Date
from Packages as p1
inner join Distribution as d1
on p1.id = d1.id
inner join (
select
Name,
Arch,
repo,
max(Date) as Date
from Packages
inner join Distribution
on Packages.id = Distribution.id
group by
Name,
Arch,
repo
) as sq
on p1.Name = sq.Name and p1.Arch = sq.Arch and d1.repo = sq.repo and p1.Date = sq.Date
问题是它似乎没有正确地分组回购。它没有给我一个独特的回购。
编辑:我想获得每个回购的最新版本。所以我必须在每个回购中获得最大日期,然后进行分组。
编辑2:我稍微用了一个答案来解决这个问题:
select p1.Name, p1.Version, p1.Arch, d1.repo, p1.Date
from Packages as p1 inner join
Distribution as d1
on p1.id = d1.id inner join (
select Name, Arch, repo, max(Date) as Date
from Packages inner join Distribution
on Packages.id = Distribution.id
group by Name, Arch, repo
) as sq
on p1.Name = sq.Name and p1.Arch = sq.Arch and d1.repo = sq.repo and p1.Date = sq.Date
这似乎对我有用。
答案 0 :(得分:1)
我认为您要从最大查询中删除repo
:
select p1.Name, p1.Version, p1.Arch, d1.repo, p1.Date
from Packages p1 inner join
Distribution d1
on p1.id = d1.id inner join
(select Name, Arch, max(Date) as Date
from Packages
group by Name, Arch
) sq
on p1.Name = sq.Name and p1.Arch = sq.Arch and p1.Date = sq.Date;
编辑:
如果并非所有repos都有日期,那么您希望通过子查询中的分布进行过滤。但是,您仍然不希望将repo
放在聚合中:
select p1.Name, p1.Version, p1.Arch, d1.repo, p1.Date
from Packages p1 inner join
Distribution d1
on p1.id = d1.id inner join
(select Name, Arch, max(Date) as Date
from Packages p join
Distribution d
on p.id = d.id
group by Name, Arch
) sq
on p1.Name = sq.Name and p1.Arch = sq.Arch and p1.Date = sq.Date;