0

私は次のものを持っています

id eventid  startdate enddate

1 1     2009-01-03 2009-01-05
1 2     2009-01-05 2009-01-09
1 3     2009-01-12 2009-01-15

すべてのイベント ID に関連する欠落している日付を生成する方法は?

編集: 欠落しているギャップは、eventid に基づいて見つける必要があります。たとえば、eventid 1 の場合、出力は 1/3/2009,1/4/2009,1/5/2009.. eventtype id 2 の場合、1/5/2009、1/6/2009... となります。 /2009/9 など

私の仕事は、与えられた 2 つの日付の間に欠落している日付を見つけることです。

これが私がこれまでに行ったすべてのことです

declare @tblRegistration table(id int primary key,startdate date,enddate date)
insert into @tblRegistration 
        select 1,'1/1/2009','1/15/2009'
declare @tblEvent table(id int,eventid int primary key,startdate date,enddate date)
insert into @tblEvent 
        select 1,1,'1/3/2009','1/5/2009' union all
        select 1,2,'1/5/2009','1/9/2009' union all
        select 1,3,'1/12/2009','1/15/2009'

;with generateCalender_cte as
(
    select cast((select  startdate from @tblRegistration where id = 1 )as datetime) DateValue
       union all
        select DateValue + 1
        from    generateCalender_cte   
        where   DateValue + 1 <= (select enddate from @tblRegistration where id = 1)
)
select DateValue as missingdates from generateCalender_cte
where DateValue not between '1/3/2009' and '1/5/2009'
and DateValue not between '1/5/2009' and '1/9/2009'
and DateValue not between '1/12/2009'and'1/15/2009'

実際に私がやろうとしているのは、カレンダーテーブルを生成し、そこからIDに基づいて欠落している日付を見つけようとしているということです

理想的な出力は

eventid                    missingdates

1             2009-01-01 00:00:00.000

1             2009-01-02 00:00:00.000

3             2009-01-10 00:00:00.000

3            2009-01-11 00:00:00.000

また、SET BASED である必要があり、開始日と終了日をハードコーディングしないでください。

事前に感謝

4

2 に答える 2

3

以下は、再帰的な CTE (SQL Server 2005 以降) を使用します。

WITH dates AS (
     SELECT CAST('2009-01-01' AS DATETIME) 'date'
     UNION ALL
     SELECT DATEADD(dd, 1, t.date) 
       FROM dates t
      WHERE DATEADD(dd, 1, t.date) <= '2009-02-01')
SELECT t.eventid, d.date
  FROM dates d 
  JOIN TABLE t ON d.date BETWEEN t.startdate AND t.enddate

DATEADD関数を使用して日付を生成します。パラメータとして開始日と終了日を取るように変更できます。KM のコメントによると、数値表のトリックを使用するよりも高速です。

于 2009-11-02T06:06:48.987 に答える
1

rexemのように-必要な一連の日時間隔を生成するために、同様のCTEを含む関数を作成しました。あなたがしているように日時間隔でデータを要約するのに非常に便利です。より詳細な投稿と関数のソースコードはここにあります:

何もないクエリからの戻りに日付を挿入します

「日付別のイベント数」を取得すると、欠落している日付はカウントが0の日付になります。

于 2009-11-02T06:14:50.143 に答える