Pregunta

Si selecciono entre un grupo de tabla por mes, día, año, solo devuelve filas con registros y combinaciones de ida y deja fuera sin ningún registro, lo que hace que aparezca de un vistazo que todos los días o mes tiene actividad, debe mirar la fecha columna activamente para huecos.¿Cómo puedo obtener una fila para cada día/mes/año, incluso cuando no hay datos presentes, en T-SQL?

¿Fue útil?

Solución 2

mi desarrollador Me respondió con este código, los guiones bajos se convirtieron en guiones porque StackOverflow estaba alterando los guiones bajos; no se requiere una tabla de números.Nuestro ejemplo se complica un poco por una unión a otra tabla, pero tal vez el ejemplo de código ayude a alguien algún día.

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 

Otros consejos

Cree una tabla de calendario y una combinación externa en esa tabla

Considere usar un tabla de números.Si bien puede ser complicado, es el mejor método que he encontrado para consultar rápidamente los datos faltantes, mostrar todas las fechas o cualquier cosa en la que desee examinar los valores dentro de un rango, independientemente de si se utilizan todos los valores de ese rango.

Sobre la base de lo que dijo SQLMenace, puede usar CROSS JOIN para completar rápidamente la tabla o crearla de manera eficiente en la memoria.
http://www.sitepoint.com/forums/showthread.php?t=562806

La tarea requiere un conjunto completo de fechas que se unirán a la izquierda en sus datos, como


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]

donde la función con valores de tabla tvfUtilGenerateIntegerList se define como


-- 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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top