按月分组取决于上个月的日期

时间:2015-08-07 03:45:36

标签: mysql sql date greatest-n-per-group

我想根据最后日期进行逐月分组查询。

在我的表格中:

july

2015-07-02

2015-07-03 

august

2015-08-04

这是我的疑问:

   SELECT DISTINCT Visit_Date FROM tr_visit 
   JOIN tm_child ON tm_child.Child_ID = tr_visit.Child_ID 
   WHERE tr_visit.Child_ID='CH001'
   GROUP BY YEAR(tr_visit.Visit_Date), MONTH(tr_visit.Visit_Date) DESC

我的结果是:

2015-07-02
 and 2015-08-04

如何选择七月份的最后一次访问,结果如下:

2015-07-03 (last visit in july)
 and 2015-08-04 (last visit in august)

1 个答案:

答案 0 :(得分:1)

像这样?

select max(visit_date)
from tr_visit
group by year(visit_date), month(visit_date);