1

以下のような data.frame があります。

toolid          startdate       enddate         stage
abc                 1-Jan-13    5-Jan-13    production
abc                 6-Jan-13    10-Jan-13   down
xyz                 3-Jan-13    8-Jan-13    production
xyz                 9-Jan-13    15-Jan-13   down

以下のような最終出力を得たいと思います。出力を返す必要があります - 1jan13 から 15jan13 (またはユーザーが希望する任意の日付範囲) までの各日における各ステージ (2 つ以上のステージがある可能性があります) の数。Rで必要な結果を作成できました。また、SQLでカーソルを作成し、目的を達成しました。しかし、カーソルを使わずに同じことをする方法はありますか? 私は論理と方向性を探しています。

         date down production
1  2013-01-01    0          1
2  2013-01-02    0          1
3  2013-01-03    0          2
4  2013-01-04    0          2
5  2013-01-05    0          2
6  2013-01-06    1          1
7  2013-01-07    1          1
8  2013-01-08    1          1
9  2013-01-09    2          0
10 2013-01-10    2          0
11 2013-01-11    1          0
12 2013-01-12    1          0
13 2013-01-13    1          0
14 2013-01-14    1          0
15 2013-01-15    1          0
4

1 に答える 1

3

これはあなたが望むものかもしれないと思います。範囲内の各日の行を取得するには、再帰的な CTE が必要です。

with daterange as (
    select startdate=min(startdate),enddate=max(enddate) from #source
), dates as (
    select d=(select startdate from daterange) union all
    select dateadd(day,1,d) from dates where d<(select enddate from daterange)
)
select 
    d,
    down=(select count(*) from #source where d between startdate and enddate and stage='down'),
    production=(select count(*) from #source where d between startdate and enddate and stage='production')
from dates
order by d;
于 2013-09-19T21:21:44.973 に答える