上月入职人数取不出来

题目要求

image.png

自己写的sql

select

a.datetime as 年月,

a.entry_num as 入职人数,

b.entry_num as 上月入职人数,

b.entry_num as 上年同期入职人数 

from (select te.year, te.month,te.datetime,te.entry_num from  (select left(datetime,4) as year ,SUBSTR(datetime,6,2) as month ,datetime,entry_num,leave_num  from student_2007 ) as te where te.year = '2019' order by te.month) a

left join (select te.year, te.month,te.datetime,te.entry_num from  (select left(datetime,4) as year ,SUBSTR(datetime,6,2) as month ,datetime,entry_num,leave_num  from student_2007 ) as te where te.year = '2018' order by te.month

) b

on a.year=b.year+1

and a.month=b.month

where a.year = '2019'

问题 datetime数据类型是varchar类型的 

image.png

评论区测试一

image.png

测试二

image.png

FineReport 南巷尕杰 发布于 2022-1-6 11:42 (编辑于 2022-1-6 14:10)
1min目标场景问卷 立即参与
回答问题
悬赏:3 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共2回答
最佳回答
0
snrtuemcLv8专家互助
发布于2022-1-6 11:44(编辑于 2022-1-6 13:41)

参考

select a.*,b.同期 from (select substr(入职日期,6,2) m,入职日期,入职人数 from aTQ where substr(入职日期,1,4)='2019') a

left join (select  substr(入职日期,6,2) m,入职日期,入职人数 as 同期 from aTQ where substr(入职日期,1,4)='2018' ) b on a.m=b.m

image.png

原始数据

image.png

=================

select a.*,b.同期,c.上期 from (select substr(入职日期,6,2)*1 m,入职日期,入职人数 from aTQ where substr(入职日期,1,4)='2019') a

left join (select  substr(入职日期,6,2)*1 m,入职日期,入职人数 as 同期 from aTQ where substr(入职日期,1,4)='2018' ) b on a.m=b.m

left join

(select substr(入职日期,6,2)+1 m,入职日期,入职人数 as 上期 from aTQ where substr(入职日期,1,4)='2019'

union

select (case when substr(入职日期,6,2)*1=12 then 1 end) m,入职日期,入职人数 as 上期 from aTQ where substr(入职日期,1,4)='2018'

) c on a.m=c.m

image.png

  • 南巷尕杰 南巷尕杰(提问者) 入职人数 和同期我能查出来 但是上月入职人数 因为不知道怎么将varchar类型的datetime日期加减就不会取(2019-01上月就是2018-12)
    2022-01-06 11:49 
  • snrtuemc snrtuemc 回复 南巷尕杰(提问者) 看修改答案,处理了,
    2022-01-06 13:40 
  • 南巷尕杰 南巷尕杰(提问者) 回复 snrtuemc 牛呀牛 后面的 (select substr(datetime,6,2)+1 m,datetime,entry_num as 上月入职人数 from student_2007 where substr(datetime,1,4)=\'2019\' union select (case when substr(datetime,6,2)*1=12 then 1 end) m,datetime,entry_num as 上月入职人数 from student_2007 where substr(datetime,1,4)=\'2018\' ) c on a.m=c.m 这段我好好看看
    2022-01-06 14:10 
  • 南巷尕杰 南巷尕杰(提问者) 回复 snrtuemc 感谢大佬
    2022-01-06 14:11 
最佳回答
0
Z4u3z1Lv6专家互助
发布于2022-1-6 11:50

前面不变

on CONVERT(INT,a.year)=CONVERT(INT,b.year)+1

and a.month=b.month

where a.year = '2019'

  • 南巷尕杰 南巷尕杰(提问者) 刚试 好像不大行(看评论区测试一) 上面完善问题了
    2022-01-06 11:54 
  • Z4u3z1 Z4u3z1 回复 南巷尕杰(提问者) MYSQL............ 不能用convert() 用cast()函数 https://jingyan.baidu.com/article/2d5afd691eab6085a2e28e92.html
    2022-01-06 11:56 
  • 南巷尕杰 南巷尕杰(提问者) 回复 Z4u3z1 还是有点不明白 用cast将日期年转换成数字+-吗
    2022-01-06 12:20 
  • Z4u3z1 Z4u3z1 回复 南巷尕杰(提问者) on cast(a.year as int)=cast(b.year as int)+1
    2022-01-06 12:50 
  • 南巷尕杰 南巷尕杰(提问者) 回复 Z4u3z1 不对 这个条件是将年份+1 对吧 我之前的条件是可以满足这个条件的on a.year=b.year+1
    2022-01-06 13:36 
  • 2关注人数
  • 369浏览人数
  • 最后回答于:2022-1-6 14:10
    请选择关闭问题的原因
    确定 取消
    返回顶部