从日期列中选择参考MAX(addDate)的列

时间:2011-11-18 13:49:00

标签: mysql database

我有这个ai_invoice表。

enter image description here

我想选择lastPaymentAmount和lastPaymentDate并引用日期列。

对于lastPaymentDate,我使用MySQL MAX()这就是我所做的。

SELECT 
  SUM(ai_account.amount) as amountPaid, 
  MAX(ai_account.addDate) as lastPaymentDate 
FROM ai_account 
WHERE ai_account.trader_id = :traderId

我对如何基于lastPaymentDate选择lastPaymentAmount感到困惑。我期待的结果是3434

2 个答案:

答案 0 :(得分:2)

这是你必须做的事情

SELECT 
  ai_account.amount as amountPaid, 
  ai_account.addDate as lastPaymentDate 
FROM ai_account 
WHERE ai_account.id = (
    SELECT 
    id
    FROM ai_account 
    WHERE ai_account.trader_id = :traderId
    ORDER BY ai_account.addDate DESC
    LIMIT 1
    )

答案 1 :(得分:2)

SELECT 
  ai_account.amount as amountPaid, 
  ai_account.addDate as lastPaymentDate 
FROM ai_account 
WHERE ai_account.addDate = (SELECT MAX(ai_account.addDate) FROM ai_account
  WHERE ai_account.trader_id = :traderId) AND ai_account.trader_id = :traderId;

子查询从ai_account.addDate中选择最后一个traderId,并且父WHERE子句将行强制为此日期和此ID。

这可能导致多于一条记录(同一交易商同一天的两个联排)。为了克服这个问题,你可以使用

SELECT 
  SUM(ai_account.amount) as amountPaid, 
  MAX(ai_account.addDate) as lastPaymentDate 
...