mysql选择最大日期直到第一次丢失

i34xakig  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(300)

我需要选择最大日期,直到每月第一个丢失的日期
我的table看起来像这样

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

下面是最好的选择方法

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百万记录

eimct9ow

eimct9ow1#

我可以通过将月份和日期分开列来修复它

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

这使得使用正确的索引速度更快

相关问题