SQL在同一查询中使用order by和group by

时间:2016-04-06 08:23:43

标签: mysql sql

我正在尝试在MySQL中运行此查询:

SELECT * 
FROM billing_invoices 
WHERE reminder <> '' 
GROUP BY customer_sequence 
ORDER BY reminder DESC

所以我希望从reminder列获取最新日期,但它显示的是最早的日期

我是否正确使用group by

1 个答案:

答案 0 :(得分:4)

您可以使用分组来获取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