我在这里得到了这些查询字符串......
SELECT
c.clientid, c.clientname, c.billingdate,
i.total - (select ifnull(sum(p.amount), 0) from payment p
where p.invoice = i.invoiceid Order by i.invoiceid) AS remaining
FROM
client c
INNER JOIN
invoice i
WHERE
c.clientid = i.client
ORDER BY
clientname
它的作用是,它获取所有客户的清单,他们的开票日期和余额。我还为客户开具发票,每张发票都有余额。我想要做的是为每个客户端获取客户最新的剩余余额(具有最高id值的发票)。
我所查询的内容是每个客户多次列出每个客户的每个剩余余额......就像这样
client 1 0.00
client 1 1.00
client 1 3.00
我正在寻找的是
client 1 0.00
client 2 3.00
client 3 5.00
我希望我有意义。我也试过Order by MAX(i.invoiceid)
,但只返回一个客户端。
答案 0 :(得分:1)
我不确定为什么max invoiceid不适合你
SELECT
c.clientid, c.clientname, c.billingdate,
i.total - (select ifnull(sum(p.amount), 0) from payment p
where p.invoice = i.invoiceid Order by i.invoiceid) AS remaining
FROM
client c
INNER JOIN
invoice i
WHERE
c.clientid = i.client
AND i.invoiceid = (SELECT MAX(i2.invoiceid) FROM invoice i2 WHERE i2.client = i.client)
ORDER BY
clientname
现在您应该只获取客户最新发票
答案 1 :(得分:0)
试试这个:
SELECT c.clientid, c.clientname, c.billingdate, i.total -
(select ifnull(sum(p.amount), 0) from payment p where p.invoice = i.invoiceid Order by i.invoiceid DESC LIMIT 1) AS remaining
FROM client c inner join invoice i where c.clientid = i.client ORDER BY clientname
使用DESCending订单和LIMIT 1,您将只为每个客户选择一个金额,ID最高的金额(因此是最新的)