我是使用 Teradata SQL 的新手,我需要根据开始和结束日期对员工进行每月计数。假设我有四个员工的数据,其中两个在 2012 年 4 月 30 日仍在工作,所以看起来像这样
Emp_ID join_date leave_date
1 1-1-2012 2-02-2012
2 1-17-2012 3-4-2012
3 2-1-2012 1-1-9999
4 3-20-2012 1-1-9999
期望的输出:
MonthEnd Emp_Count
1-31-2012 2
2-29-2012 2
3-31-2012 1
4-30-2012 2
有没有比 UNION ALL 一堆 Selects 更优雅的方法来做到这一点?
select
'1-31-2012' as MonthEnd
Count(Emp_ID) as Emp_Count
where join_date <= MonthEnd and leave_date > MonthEnd
UNION ALL
select
'2-29-2012' as MonthEnd
Count(Emp_ID) as Emp_Count
where join_date <= MonthEnd and leave_date > MonthEnd
UNION ALL
select
'3-31-2012' as MonthEnd
Count(Emp_ID) as Emp_Count
where join_date <= MonthEnd and leave_date > MonthEnd
UNION ALL
select
'4-30-2012' as MonthEnd
Count(Emp_ID) as Emp_Count
where join_date <= MonthEnd and leave_date > MonthEnd
还要忽略数据格式问题,因为这些问题已经处理好了。