2012-08-29 60 views
0

我在這裏得到了這些查詢字符串...SQL馬克斯得到最高的ID

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),但只返回一個客戶端。

回答

1

我不是知道爲什麼最大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 

現在你應該只得到了客戶的最新發票

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 

與從大到小的順序和限制1,您將只選擇每個客戶端ONE量,最高的ID量(因而最新的)

+0

我用相同的結果試過了你的代碼。根據客戶有多少發票重複客戶端 – user1269625