SQL - 基于开始日期和结束日期的每月计数

时间:2013-06-06 15:08:55

标签: sql teradata

我是使用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的一堆选择?

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

同时忽略数据格式问题,因为这些问题已经得到解决。

3 个答案:

答案 0 :(得分:1)

执行此操作的标准SQL方法是将日期放入表或子查询中,然后使用left outer joingroup by来获取计数。这是一个例子:

select dates.MonthEnd, COUNT(*)
from (select cast('2012-01-31' as date) as MonthEnd union all
      select '2012-02-29' union all
      . . .
     ) dates left outer join
     employees e
     on e.join_date <= dates.MonthEnd and (e.leave_Date > MonthEnd or e.leave_Date is null)
group by dates.MonthEnd
order by dates.MonthEnd;

答案 1 :(得分:1)

在TD13.10中,您可以使用EXPAND ON在雇佣期内每个月创建一行

SELECT MonthEnd, COUNT(*)
FROM
 (
   SELECT 
      BEGIN(pd) AS MonthEnd
   FROM tab 
   EXPAND ON PERIOD(join_date, leave_date) AS pd
   BY ANCHOR MONTH_END -- one row for each month end 
   FOR PERIOD (DATE '2012-01-01', DATE '2012-05-30') -- the range of dates required for output 
 ) AS dt
GROUP BY 1
ORDER BY 1

迪特

答案 2 :(得分:0)

&GT;

CREATE TABLE Table1
    ([Emp_ID] int, [join_date] datetime, [leave_date] datetime)
;

INSERT INTO Table1
([Emp_ID], [join_date], [leave_date])
VALUES
(1, '2012-01-01 00:00:00', '2012-02-02 00:00:00'),
(2, '2012-01-17 00:00:00', '2012-03-04 00:00:00'),
(3, '2012-02-01 00:00:00', '9999-01-01 00:00:00'),
(4, '2012-03-20 00:00:00', '9999-01-01 00:00:00')
;





declare @output table 
(monthyear nvarchar(10),ENDING_MONTH nvarchar(10))


insert into @output
select convert(nvarchar(5),month(join_date)) + convert(nvarchar(10),year(join_date)) 
as 'monthyear', 
convert(date,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,join_date)+1,0))) as ENDING_MONTH
from Table1


select ENDING_MONTH, count(ENDING_MONTH) from @output group by ENDING_MONTH

sqlfiddle

相关问题