0

有两个表:人员和发票每个人都有很多发票行,我想选择所有人员信息以及他们最后的发票金额。

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
4

2 回答 2

0

由于同一个人可以在同一日期进行多次付款,因此您需要一种打破平局以找到最新付款的方法。虽然不是很好..你可以使用ID列(自动编号)。但是,这需要一个额外的查询:一个获取最大日期,另一个获取该ID日期的最大值。

SELECT p.code, i.[Date], i.amount
FROM   Person p INNER  JOIN 
    (  Invoice i INNER JOIN
          (
              SELECT MAX(mxi.ID) AS MaxID, mxi.person_code, mxd.latestDate
              FROM  Invoice mxi INNER JOIN 
                       (
                          SELECT person_code, MAX([Date]) AS LatestDate
                          FROM   Invoice
                          GROUP BY person_code
                        ) mxd ON mxd.person_code = mxi.person_code AND mxd.latestDate = mxi.[Date]
              GROUP BY  mxi.person_code, mxd.latestDate
           )  lt ON lt.MaxID = i.ID
     ) ON p.code = i.person_code

现在解决问题。上面的查询一直有效,直到您将第一个联接从 更改INNERLEFT。然后 Access 抱怨它太复杂/模棱两可。(也许更熟悉 Access 的人可以重写它以满足其限制。)否则,您可能必须将部分 sql 拆分为视图/存储查询。然后加入视图/存储的查询。就像我说的......它经常变得令人费解。但这是我能想到的让 Access 开心的唯一方法。

vLatestInvoice(存储查询/查看)

SELECT i.ID, i.person_code,  i.[Date], i.amount
FROM   Invoice AS i INNER JOIN 
         (   SELECT MAX(mxi.ID) AS MaxID, mxi.person_code, mxd.latestDate
             FROM  Invoice mxi INNER JOIN 
                      (
                         SELECT person_code, MAX([Date]) AS LatestDate
                         FROM   Invoice
                         GROUP BY person_code
                      ) mxd ON mxd.person_code = mxi.person_code AND mxd.latestDate = mxi.[Date]
             GROUP BY  mxi.person_code, mxd.latestDate
         ) AS lt ON lt.MaxID = i.ID;

主要查询:

SELECT p.code, l.[Date], l.amount
FROM Person p LEFT JOIN vLatestInvoice l ON l.person_code = p.code
于 2012-04-06T15:20:23.533 回答
0

你可以做

SELECT p.code, p.name, i.amount
FROM person p
INNER JOIN invoice i on i.person_code = p.code AND i.date = 
  (SELECT MAX(date) FROM invoice WHERE person_code = p.code)
AND i.ID = (SELECT MAX(ID) FROM invoice where person_code = p.code AND ID = i.ID)

我已经对此进行了测试,并且效果很好!

于 2012-04-05T11:09:05.083 回答