我正在尝试在MySQL中运行此查询:
SELECT *
FROM billing_invoices
WHERE reminder <> ''
GROUP BY customer_sequence
ORDER BY reminder DESC
所以我想从
reminder
列中获取最新日期,但是它显示最早的日期我是否错误地使用
group by
? 最佳答案
您可以使用分组以获取每个customer_sequence
的最新记录:
SELECT customer_sequence, MAX(reminder) AS max_reminder
FROM billing_invoices
WHERE reminder <> ''
GROUP BY customer_sequence
然后重新连接到原始表以获取其余字段:
SELECT t1.*
FROM billing_invoices AS t1
INNER JOIN (
SELECT customer_sequence, MAX(reminder) AS max_reminder
FROM billing_invoices
WHERE reminder <> ''
GROUP BY customer_sequence
) AS t2 ON t1.customer_sequence = t2.customer_sequence AND
t1.reminder = t2.max_reminder
关于mysql - SQL在同一查询中使用order by和group by,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36445436/