最大ID号的子查询

时间:2015-05-12 11:05:23

标签: sql ms-access group-by max

我有一个查询,我正在尝试过滤报告。每个addressID可以有多个作业,每个作业可以有多个元素。

基本上我试图获得每个addressID的最大jobID,但我想获得该工作的每个元素。

当前的查询结果是:

+-----------+-------+--------+
| AddressID | JobID | Cost   |
+-----------+-------+--------+
| 326       | 328   | £52.50 |
| 327       | 329   | £55.13 |
| 328       | 330   | £57.88 |
| 329       | 331   | £60.78 |
| 329       | 331   | £63.81 |
| 330       | 332   | £67.00 |
| 330       | 332   | £70.36 |
| 330       | 332   | £73.87 |
| 330       | 332   | £77.57 |
| 330       | 333   | £57.75 |
| 330       | 333   | £60.64 |
| 330       | 333   | £63.67 |
| 330       | 333   | £66.85 |
| 331       | 334   | £70.20 |
| 331       | 334   | £73.71 |
| 331       | 335   | £77.39 |
| 331       | 336   | £81.26 |
| 331       | 336   | £85.32 |
| 331       | 336   | £89.59 |
+-----------+-------+--------+

我想要得到:

+-----------+-------+--------+
| AddressID | JobID | Cost   |
+-----------+-------+--------+
| 326       | 328   | £52.50 |
| 327       | 329   | £55.13 |
| 328       | 330   | £57.88 |
| 329       | 331   | £60.78 |
| 329       | 331   | £63.81 |
| 330       | 333   | £57.75 |
| 330       | 333   | £60.64 |
| 330       | 333   | £63.67 |
| 330       | 333   | £66.85 |
| 331       | 336   | £81.26 |
| 331       | 336   | £85.32 |
| 331       | 336   | £89.59 |
+-----------+-------+--------+

我一直在查看SELECT TOP 1以隔离MAX JobID,但最终将查询限制为仅1个条目。

目前正在调整此子查询,但仍不确定我是否在正确的轨道上:

(SELECT Max(vusearch.JobID) FROM vuSearch AS T WHERE PAID = vuSearch.AddressID GROUP BY AddressID)

有人可以提供建议吗?

2 个答案:

答案 0 :(得分:4)

这是一种方法:

select v.*
from vusearch as v
where v.JobId = (select max(v2.JobId)
                 from vusearch as v2
                 where v2.AddressId = v.AddressId
                );

答案 1 :(得分:1)

管理得到修复 - 我可能没有提供足够的信息,因为我试图让我的解释变得简单。

非常感谢你的帮助戈登

((vuSearch.PDID)IN((SELECT Max(v2.PDID)FROM vuSearch AS v2 GROUP BY v2.PAID)))