1

Teradata SQL を使用するのは初めてで、開始日と終了日に基づいて毎月の従業員数を数える必要があります。4 人の従業員のデータがあり、そのうち 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

望ましい出力:

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

これを行うためのよりエレガントな方法はありますか?

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

これを行う標準的な SQL の方法は、日付をテーブルまたはサブクエリに入れ、and を使用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;
于 2013-06-06T15:16:24.540 に答える