문제

월, 일, 연도까지 테이블 그룹에서 선택하면 레코드가있는 행만 반환하고 레코드없이 조합을 방치하여 매일 또는 달이 활동을 한 눈에 보이면 날짜를 살펴 봐야합니다. 틈에 적극적으로 열.T-SQL에서 데이터가 없는 경우에도 매일/월/연도에 대한 행을 어떻게 얻을 수 있나요?

도움이 되었습니까?

해결책 2

내 개발자 이 코드가 나에게 돌아왔습니다. StackOverflow가 밑줄을 맹글링했기 때문에 밑줄이 대시로 변환되었습니다. 숫자 테이블은 필요하지 않습니다.우리의 예는 다른 테이블에 대한 조인으로 인해 약간 복잡하지만 언젠가는 코드 예가 ​​누군가에게 도움이 될 것입니다.

declare @career-fair-id int 
select @career-fair-id = 125

create table #data ([date] datetime null, [cumulative] int null) 

declare @event-date datetime, @current-process-date datetime, @day-count int 
select @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id) 
select @current-process-date = dateadd(day, -90, @event-date) 

    while @event-date <> @current-process-date 
    begin 
    select @current-process-date = dateadd(day, 1, @current-process-date) 
    select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id) 
        if @current-process-date <= getdate() 
        insert into #data ([date], [cumulative]) values(@current-process-date, @day-count) 
    end 

    select * from #data 
    drop table #data 

다른 팁

달력 테이블을 만들고 해당 테이블에 외부 조인을 만듭니다.

사용을 살펴보세요 숫자 테이블.해킹적일 수 있지만 누락된 데이터를 빠르게 쿼리하거나 모든 날짜를 표시하거나 해당 범위의 모든 값이 사용되는지 여부에 관계없이 범위 내의 값을 검사하려는 모든 항목을 표시하는 가장 좋은 방법입니다.

SQLMenace의 말을 바탕으로 CROSS JOIN을 사용하여 테이블을 빠르게 채우거나 메모리에 효율적으로 생성할 수 있습니다.
http://www.sitepoint.com/forums/showthread.php?t=562806

이 작업에서는 다음과 같이 데이터에 왼쪽 조인할 전체 날짜 집합이 필요합니다.


DECLARE @StartInt int
DECLARE @Increment int
DECLARE @Iterations int

SET @StartInt = 0
SET @Increment = 1
SET @Iterations = 365


SELECT
    tCompleteDateSet.[Date]
  ,AggregatedMeasure = SUM(ISNULL(t.Data, 0))
FROM
        (

            SELECT
                [Date] = dateadd(dd,GeneratedInt, @StartDate)
            FROM
                [dbo].[tvfUtilGenerateIntegerList] (
                        @StartInt,
                        ,@Increment,
                        ,@Iterations
                    )
            ) tCompleteDateSet
    LEFT JOIN tblData t
          ON (t.[Date] = tCompleteDateSet.[Date])
GROUP BY
tCompleteDateSet.[Date]

여기서 테이블 반환 함수 tvfUtilGenerateIntegerList는 다음과 같이 정의됩니다.


-- Example Inputs

-- DECLARE @StartInt int
-- DECLARE @Increment int
-- DECLARE @Iterations int
-- SET @StartInt = 56200
-- SET @Increment = 1
-- SET @Iterations = 400
-- DECLARE @tblResults TABLE
-- (
--     IterationId int identity(1,1),
--     GeneratedInt int
-- )


-- =============================================
-- Author: 6eorge Jetson
-- Create date: 11/22/3333
-- Description: Generates and returns the desired list of integers as a table
-- =============================================
CREATE FUNCTION [dbo].[tvfUtilGenerateIntegerList]
(
    @StartInt int,
    @Increment int,
  @Iterations int
)
RETURNS
@tblResults TABLE
(
    IterationId int identity(1,1),
    GeneratedInt int
)
AS
BEGIN

  DECLARE @counter int
  SET @counter= 0
  WHILE (@counter < @Iterations)
    BEGIN
    INSERT @tblResults(GeneratedInt) VALUES(@StartInt + @counter*@Increment)
    SET @counter = @counter + 1
    END


  RETURN
END
--Debug
--SELECT * FROM @tblResults

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top