我需要选择最长日期,直到第一个缺失日期
我的表看起来像这样
ClientID DATE
1 2018-01-01
1 2018-02-01
1 2018-03-01
1 2018-04-01
1 2018-05-01
1 2018-07-01
1 2018-08-01
1 2018-09-01
1 2018-10-01
1 2018-11-01
1 2018-12-01
2 2018-01-01
2 2018-02-01
2 2018-03-01
2 2018-04-01
2 2018-05-01
2 2018-06-01
2 2018-07-01
2 2018-08-01
2 2018-09-01
2 2018-11-01
2 2018-12-01
最好的方法是选择像bellow
ClientID DATE
1 2018-05-01
2 2018-09-01
我这样做
update temporaryTable a
(SELECT max(date), clientID FROM table WHERE DATE_FORMAT(date, '%Y%m') = DATE_FORMAT(NOW(), '%Y%m') group by clientID) b on a.clientID = b.clientID
set a.date = b.date;
update temporaryTable a
(SELECT max(date), clientID FROM table WHERE DATE_FORMAT(date, '%Y%m') = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 month), '%Y%m') group by clientID) b on a.clientID = b.clientID
set a.date = b.date
where a.date = DATE_FORMAT(NOW(), '%Y%m');
update temporaryTable a
(SELECT max(date), clientID FROM table WHERE DATE_FORMAT(date, '%Y%m') = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 2 month), '%Y%m') group by clientID) b on a.clientID = b.clientID
set a.date = b.date
where a.date = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 month), '%Y%m);
等......直到24个月
我不喜欢它而且它很慢,因为该表有3密耳的记录
答案 0 :(得分:0)
我能够通过在单独的列中分隔月份和日期来修复它
update table set month_date=MONTH(DATE), year_date = YEAR(DATE);
然后我用了这个
SELECT clientID, year_date, min(month_date) as date_month
FROM table a
WHERE NOT EXISTS (SELECT c.clientID, c.year_date, c.month_date
FROM table c
WHERE c.month_date= a.month_date + 1
AND c.clientID= a.clientID
AND c.year_date= a.year_date and a.year_date= year(now()) and month_date >= 1
GROUP BY a.clientID, a.year_date
这使得使用正确的索引更快了