2011-04-11 68 views
0

即時通訊使用Mysql 5.1,並給予與列customerid付款,paymentdate我需要所有客戶的最新付款。 所以用項目的表SQL:獲取所有客戶的最新付款?

row, customerid, paymentdate 
1 5   2011-03-01 
2 5   2011-04-01 
3 6   2011-01-01 
4 7   2011-01-01 
5 7   2011-02-01 

應該返回行2,3,5 查詢

select max(paymentdate),customerid from payments where customerid=5; 

,我試圖進入某種作品WHERE客戶IN(...),但沒有運氣,因爲它返回2列,不僅1

感謝


最終的答案啓發我去尋找相關的信息,並與 解決了這個問題下面的查詢(如在文章中評論)

select * from (select * from payments order by paymentdate desc) as p group by customerid; 

same problem from mysql forum solutions from a related mysql article

回答

5

你應該group by在客戶。

select max(paymentdate),customerid from payments group by customerid; 
-1

另一種方法:

Select paymentdate,customerid from payments group by customerid order by paymentdate DESC; 

甚至:

Select distinct(customerid),paymentdate from payments order by paymentdate DESC; 

添加DESC的原因首先要返回最近的日期排序。

+0

這些查詢都沒有返回預期的結果 - 我認爲這是因爲表中的條目順序。也許我是錯的,但例如第一個查詢按customerid分組,然後按paymentdate排序。因爲例如舊條目(舊付款日期)在新條目之前,舊條目被分組然後排序,因此不起作用 – 2011-04-12 05:31:41

相關問題