복붙노트

[SQL] 날짜 범위 사이에 날짜를 얻기

SQL

날짜 범위 사이에 날짜를 얻기

나는 2005 SQL Server를 사용하여 날짜 범위에있는 모든 날짜를 얻을 필요

해결법

  1. ==============================

    1.여기 가서 :

    여기 가서 :

    DECLARE @DateFrom smalldatetime, @DateTo smalldatetime;
    SET @DateFrom='20000101';
    SET @DateTo='20081231';
    -------------------------------
    WITH T(date)
    AS
    ( 
    SELECT @DateFrom 
    UNION ALL
    SELECT DateAdd(day,1,T.date) FROM T WHERE T.date < @DateTo
    )
    SELECT date FROM T OPTION (MAXRECURSION 32767);
    
  2. ==============================

    2.당신은 테이블에 날짜가 간단하게 사용할 수있는 두 날짜 사이의 사람들을 선택합니다

    당신은 테이블에 날짜가 간단하게 사용할 수있는 두 날짜 사이의 사람들을 선택합니다

    select * from yourTable where yourDate between date1 and date2
    

    당신은 아무것도에서 날짜를 생성 할 경우에 당신은 루프와 함께 할 수있는 또는 당신이 날짜로 임시 테이블을 채우고 그에서 선택할 수 있습니다.

  3. ==============================

    3.

    DECLARE @Date1 DATE='2016-12-21', @Date2 DATE='2016-12-25'
    SELECT DATEADD(DAY,number,@Date1) [Date] FROM master..spt_values WHERE type = 'P' AND DATEADD(DAY,number,@Date1) <= @Date2
    
  4. ==============================

    4.약간 더 복잡하지만, 아마도 더 유연한 숫자의 연속 세트를 포함하는 테이블을 활용하는 것입니다. 이것은 다른 간격을 가진 하나 개 이상의 날짜 범위 수 있습니다.

    약간 더 복잡하지만, 아마도 더 유연한 숫자의 연속 세트를 포함하는 테이블을 활용하는 것입니다. 이것은 다른 간격을 가진 하나 개 이상의 날짜 범위 수 있습니다.

    /* holds a sequential set of number ie 0 to max */
    /* where max is the total number of rows expected */
    declare @Numbers table ( Number int  )
    
    declare @max int 
    declare @cnt int
    
    set @cnt = 0
    /* this value could be limited if you knew the total rows expected */
    set @max = 999 
    
    /* we are building the NUMBERS table on the fly */
    /* but this could be a proper table in the database */
    /* created at the point of first deployment */
    while (@cnt <= @max)
    begin
          insert into @Numbers select @cnt
          set @cnt = @cnt + 1
    end
    
    /* EXAMPLE of creating dates with different intervals */
    
    declare @DateRanges table ( 
       StartDateTime datetime, EndDateTime datetime, Interval int )
    
    /* example set of date ranges */
    insert into @DateRanges
    select '01 Jan 2009', '10 Jan 2009', 1 /* 1 day interval */
    union select '01 Feb 2009', '10 Feb 2009', 2 /* 2 day interval */
    
    /* heres the important bit generate the dates */
    select
          StartDateTime
    from
    (
          select
                d.StartDateTime as RangeStart,
                d.EndDateTime as RangeEnd,
                dateadd(DAY, d.Interval * n.Number, d.StartDateTime) as StartDateTime
          from 
                @DateRanges d, @Numbers n
    ) as dates
    where
          StartDateTime between RangeStart and RangeEnd
    order by StartDateTime
    

    나는 actully 시간 슬롯에 분할 기간이의 변형을 사용하여 (각종 간격 그러나 보통 5 분 길이). 내 @numbers 테이블은 5 개 슬롯의 총 수는 24 시간 동안 할 수 있습니다 먹으 렴 이후 288의 최대 포함되어 있습니다.

    /* EXAMPLE of creating times with different intervals */
    
    delete from @DateRanges 
    
    /* example set of date ranges */
    insert into @DateRanges
    select '01 Jan 2009 09:00:00', '01 Jan 2009 12:00:00', 30 /* 30 minutes interval */
    union select '02 Feb 2009 09:00:00', '02 Feb 2009 10:00:00', 5 /* 5 minutes interval */
    
    /* heres the import bit generate the times */
    select
          StartDateTime,
          EndDateTime
    from
    (
          select
                d.StartDateTime as RangeStart,
                d.EndDateTime as RangeEnd,
                dateadd(MINUTE, d.Interval * n.Number, d.StartDateTime) as StartDateTime,
                dateadd(MINUTE, d.Interval * (n.Number + 1) , StartDateTime) as EndDateTime
          from 
                @DateRanges d, @Numbers n
    ) as dates
    where
          StartDateTime >= RangeStart and EndDateTime <= RangeEnd
    order by StartDateTime
    
  5. ==============================

    5.여기에 최신 세대의 오라클 버전입니다 :

    여기에 최신 세대의 오라클 버전입니다 :

    SELECT TO_DATE ('01-OCT-2008') + ROWNUM - 1 g_date
      FROM all_objects
     WHERE ROWNUM <= 15
    

    대신 ALL_OBJECTS 그것의 필수 범위를 커버하기에 충분한 임의의 행 테이블 일 수있다.

  6. ==============================

    6.당신이 원하는 것은 두 날짜 사이의 데이터베이스에 존재하는 모든 날짜를 얻을 수있는 경우 (즉, 어떤 날짜 고객 2008 년 3 분기에 발주 한) 당신은 다음처럼 작성할 수 있습니다 :

    당신이 원하는 것은 두 날짜 사이의 데이터베이스에 존재하는 모든 날짜를 얻을 수있는 경우 (즉, 어떤 날짜 고객 2008 년 3 분기에 발주 한) 당신은 다음처럼 작성할 수 있습니다 :

    select distinct(orderPlacedDate) 
    from orders 
    where orderPlacedDate between '2008-07-01' and 2008-09-30' 
    order by orderPlacedDate
    
  7. ==============================

    7.날짜 범위를 생성하려면 당신은 테이블 반환 함수를 작성할 수 있습니다. 이 데이터웨어 하우스의 날짜 차원을 생성하는 기능입니다 - 당신은 아마 스페셜을 트리밍하여 매우 쉽게 적응할 수 있습니다.

    날짜 범위를 생성하려면 당신은 테이블 반환 함수를 작성할 수 있습니다. 이 데이터웨어 하우스의 날짜 차원을 생성하는 기능입니다 - 당신은 아마 스페셜을 트리밍하여 매우 쉽게 적응할 수 있습니다.

    편집 : 여기 날짜 차원 계층 구조하지 않고있다.

    if object_id ('ods.uf_DateHierarchy') is not null
        drop function ods.uf_DateHierarchy
    go
    
    create function ods.uf_DateHierarchy (
           @DateFrom datetime
          ,@DateTo   datetime
    ) returns @DateHierarchy table (
            DateKey           datetime
    ) as begin
        declare @today           datetime  
        set @today = @Datefrom
    
        while @today <= @DateTo begin
            insert @DateHierarchy (DateKey) values (@today)
            set @today = dateadd (dd, 1, @today)
        end
    
        return
    end
    
    go
    
  8. from https://stackoverflow.com/questions/271595/getting-dates-between-a-range-of-dates by cc-by-sa and MIT license