有两个表格Student 和 Change:
表Student 记录学生的入学信息:
Xh xm zt timech
20100001 张三 在学 2010.9.1
20100002 李四 在学 2010.9.1
20100003 王五 在学 2010.9.1
20100004 钱六 在学 2010.9.1
表Change 记录学生的学籍变化情况:
xuhao xh ztchange timech
1 20100001 辍学 2010.11.1
2 20100001 在学 2010.12.5
3 20100002 休学 2011.1.9
4 20100003 辍学 2011.3.9
5 20100002 在学 2011.6.6
现要求查询指定时间的在校生人数,例如2011.1.20,按上两表结果应为:
Xh xm zt timech
20100001 张三 在学 2010.12.5
20100002 李四 休学 2011.1.9
20100003 王五 在学 2010.9.1
20100004 钱六 在学 2010.9.1
张三在2011.1.1时已经复学了,所以状态为在学,但时间为最近一次变化的时间2010.12.5
李四已经休学,变化时间为2011.1.9
王五此时还没辍学,钱六一直没变,因此两人的记录都没变。
如何用SQL语句完成以上查询呢? 谢谢!
select
a.xh as xh,
a.xm as xm ,
case b.ztchange when ' ' then a.zt else b.ztchange end as zt ,
case b.timech when ' ' then a.timech else b.timech end as timech
from student a
left join change b on a.xh = b.xh and b.timech > '20110120' and b.ztchange = '在学'
希望能帮到你,别忘了采纳我的答案哦,祝你生活愉快!