1

我是使用 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

还要忽略数据格式问题,因为这些问题已经处理好了。

4

3 回答 3

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

迪特

于 2013-06-27T17:05:55.187 回答
1

执行此操作的标准 SQL 方法是将日期放入表或子查询中,然后使用left outer joinandgroup 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;
于 2013-06-06T15:16:24.540 回答
0

>

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

于 2013-06-06T16:00:24.820 回答