马上,尝试类似的东西
SELECT c.clientid,
c.clientname,
c.billingdate,
(
SELECT TOP 1
remainingbalance
FROM invoice i
WHERE i.client = c.clientid
ORDER BY i.invoiceid DESC
) AS remaining
FROM client c
ORDER BY clientname
您使用的是哪种 RDMS?
一种不同的方法如下
SELECT c.clientid,
c.clientname,
c.billingdate,
rb.remainingbalance
FROM client c INNER JOIN
(
SELECT i.clientid,
i.remainingbalance
FROM invoice i INNER JOIN
(
SELECT clientid,
MAX(invoiceid) invoiceid
FROM invoice
GROUP BY clientid
) m ON i.invoiceid = m.invoiceid
AND i.clientid = m.clientid
) rb ON c.clientid = rb.clientid
ORDER BY clientname
首先获取每个客户的“最新”发票,然后从该发票中获取所需的详细信息并与客户信息一起显示。