# 思路:看到结果表需要添加新列,想到使用连接 # --------------------------------------------- # 先获取每个岗位,每一个月内收到简历的数目存储为临时表 with t as ( select job, date_format(`date`, '%Y-%m') mon, sum(num) cnt from resume_info group by job, date_format(`date`, '%Y-%m') ) # 对临时表使用自连接来作不同年相同月份的数据匹配 select t1.job job, t1.mon first_year_mon, t1.cnt first_year_cnt, t2.mon second_year_mon, t2.cnt second_year_cnt from t t1 join t t2 on t1.job=t2.job and substring_index(t1.mon,'-',-1) = substring_index(t2.mon,'-',-1) and substring_index(t2.mon,'-',1) - substring_index(t1.mon,'-',1) = 1 where substring_index(t1.mon,'-',1) = '2025' order by first_year_mon desc, job desc;
由于使用date_format时已经把日期类型转化成字符串类型,故后续再要匹配时得适应字符串操作函数来提取相应部分进行匹配;也可以考虑当时构建临时表时将原始的date日期一并查询一个出来,例如在分组后查询个max(date)保留以方便后续匹配操作。