有两个表:人员和发票每个人都有很多发票行,我想选择所有人员信息以及他们最后的发票金额。
人
code | Name | ....
1 | name1
2 | name1
3 | name1
发票
ID | person_code | amount | date
1 | 2 | 30000 | 12
2 | 1 | 40000 | 10
3 | 3 | 50000 | 12
4 | 2 | 60000 | 14
5 | 3 | 70000 | 12
6 | 2 | 80000 | 12
7 | 1 | 90000 | 18
我要选择
person code | person name | last amount
1 | name1 | 90000
2 | name2 | 60000
3 | name3 | 70000
或者
SELECT person.code , person.name , lastinvoice.amount
FROM person
LEFT JOIN
(SELECT * FROM invoice where invoice.person_code=person.code order by date, ID) as
lastinvoice ON lastinvoice.person_code = person.code
此查询不适用于 ms 访问:
select * from invoice as i where id=(select max(id) from invoice where personCode=i.personcode and date=( select max(date) from invoice where personCode=i.PersonCode