2013-06-06 2 views
1

Teradata SQL을 처음 사용하기 때문에 시작일과 종료일을 기준으로 월별 직원 수를 계산해야합니다. 더 우아한 방법이 있나요SQL - 시작일과 종료일을 기준으로 월별 계산

MonthEnd   Emp_Count 
1-31-2012   2 
2-29-2012   2 
3-31-2012   1 
4-30-2012   2 

: 이제 난 아직도 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 

원하는 출력과 같다 이 일을하는 것보다 선택의 무리를 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 

또한 데이터 형식 문제는 이미 처리되었으므로 무시하십시오.

답변

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; 
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 
TD13.10에서

sqlfiddle

1

당신이 employement 기간

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 
내에서 매달 하나 개의 행을 만들을 확장 사용할 수 있습니다

Dieter

관련 문제