我有一个查询,显示该月最后一天的所有匹配报告(即完整月份报告)
SELECT id,
DATE_FORMAT( start_date, '%e-%b-%y' ) AS start_date,
DATE_FORMAT( end_date, '%e-%b-%y' ) AS end_date,
DATE_FORMAT( end_date, '%M %Y' ) as report_month
FROM Reports
WHERE customer_id ='2321'
AND end_of_month_file = '1'
问题是重复的 - 有些文件已被多次处理......
id start_date end_date report_month
1 1-Feb-14 28-Feb-14 February 2014
2 1-Mar-14 31-Mar-14 March 2014
3 1-Mar-14 31-Mar-14 March 2014
4 1-Mar-14 31-Mar-14 March 2014
5 1-Mar-14 31-Mar-14 March 2014
6 1-Mar-14 31-Mar-14 March 2014
7 1-Mar-14 31-Mar-14 March 2014
8 1-Mar-14 31-Mar-14 March 2014
9 1-Mar-14 31-Mar-14 March 2014
如何过滤结果,只给我每个月的最后一个/最新条目?
答案 0 :(得分:1)
使用GROUP BY
然后排序最新的:
SELECT id,
DATE_FORMAT( start_date, '%e-%b-%y' ) AS start_date,
DATE_FORMAT( end_date, '%e-%b-%y' ) AS end_date,
DATE_FORMAT( end_date, '%M %Y' ) as report_month
FROM Reports
WHERE customer_id ='2321'
AND end_of_month_file = '1'
GROUP BY start_date
ORDER BY start_date DESC;
答案 1 :(得分:0)
既然你有MySQL,为什么不使用LIMIT:
SELECT id,
DATE_FORMAT( start_date, '%e-%b-%y' ) AS start_date,
DATE_FORMAT( end_date, '%e-%b-%y' ) AS end_date,
DATE_FORMAT( end_date, '%M %Y' ) as report_month
FROM Reports
WHERE customer_id ='2321'
AND end_of_month_file = '1'
ORDER BY start_date DESC
LIMIT 1