2

我有一个棘手的问题。我有一张社会保障缴款表如下(SQL Fiddle

    IdPersona   fecha_ingreso   fecha_egreso
5690180         01/01/1987      30/11/2012
5690180         01/01/2010      30/11/2012
5690180         11/06/2012      15/11/2012
5690180         12/04/2012      25/04/2012
5690180         16/03/2012      30/03/2012
5690180         18/06/2011      15/10/2011
5690180         20/12/2012      20/01/2013
5690180         21/11/2012      15/12/2012

每行代表个人的一项工作。个人可能同时拥有一份以上的工作。我需要计算每个人在特定时期(例如去年)贡献了多少天,问题是我必须只计算不同的贡献天数,而不是对同一天多次计算一个人。我怎样才能做到这一点?


概述可能的解决方案来计算天数但不是唯一的 1-定义日期范围,一个计算人们所做贡献的时间窗口。2-对于每个 RespondentID,我必须计算在此期间输入窗口有多少天?

DECLARE @FchRef DATETIME

SET @FchRef ='2011-05-01'

--Fhc referencia de comienzo del programa a partir de cual calcular aportes
DECLARE @PeriRef SMALLINT

SET @PeriRef =24

--Periodo a partir de la Fch ref para contar aportes
DECLARE @FchCotDesde DATETIME

SET @FchCotDesde=Dateadd(MONTH, -24, @FchRef)

--Fch a partir de la cual calcular aportes
SELECT ut.documento                 'CI_UT',
       sum(DATEDIFF(DAY, CASE
                           WHEN CONVERT(DATETIME, act.fecha_ingreso, 103) < @FchCotDesde THEN @FchCotDesde
                           ELSE CONVERT(DATETIME, act.fecha_ingreso, 103)
                         END, CASE
                                WHEN fecha_egreso = '' THEN @FchRef
                                ELSE CONVERT(DATETIME, act.fecha_egreso, 103)
                              END)) 'DiasContados'
FROM   dbo.[UT2011_12] ut
       LEFT JOIN dbo.DatosPersonalesyDomicilios dat
         ON cast(cast(ut.documento AS DECIMAL(12, 0))AS VARCHAR) = dat.nro_documento
       LEFT JOIN dbo.Actividades act
         ON act.pers_identificador = dat.pers_identificador
            AND ( CONVERT(DATETIME, act.fecha_egreso, 103) = ''
                   OR CONVERT(DATETIME, act.fecha_egreso, 103) >= @FchCotDesde )
            -- La Fch de egreso es vacia ó con Fch posterior a fch ref
            AND CONVERT(DATETIME, act.fecha_ingreso, 103) <= @FchRef
--La Fch de inicio de act es anterior a la FchRef
WHERE  ut.UT_2011_Inscriptos = 1
        OR ut.UT_2012_Inscriptos = 1
GROUP  BY ut.documento 

这个解决方案的问题在于,如果日期范围(入口和出口)重叠,它就可以工作。我想到了一个解决问题的方法:1 - 创建一个包含每个人的游标 2 - 我创建了一个循环,该循环在每天的窗口期中循环,如果你抛出一个贡献和 0 但是,对于每个个人。我提出的解决方案将如何非常复杂。你能想出更好的解决方案吗?

使用此脚本,您可以创建表

        create table #aux(
        Idpersona int
        ,FechaIngreso datetime
        ,FechaEgreso  datetime
        ) 
    insert into #aux values(5690180,'1987/01/01','2012/11/30')
    insert into #aux values(5690180,'2010/01/01','2012/11/30')
    insert into #aux values(5690180,'2012/06/11','2012/11/15')
    insert into #aux values(5690180,'2012/04/12','2012/04/25')
    insert into #aux values(5690180,'2012/03/16','2012/03/30')
    insert into #aux values(5690180,'2011/06/18','2011/10/15')
    insert into #aux values(5690180,'2012/12/20','2013/01/20')
    insert into #aux values(5690180,'2012/11/21','2012/12/15')
    select * from #aux

我看问题的好方法是用一张图

111111111111111111111111111000000000000000000000000000000000000000000000000000000000
|----A1----|
         |----A2----|
               |----A3----|

00000111111111111111110000001111111111111111111111111000000000000000000000000000000
     |------B1-------|
                            |----------B2-----------|
4

2 回答 2

5

可能最简单的方法是创建一个辅助日期表。

CREATE TABLE Dates(D DATE PRIMARY KEY)

/*
Load dates between 1990-01-01 and 2049-12-31*/
INSERT INTO Dates
SELECT TOP (21915) DATEADD(DAY,ROW_NUMBER() OVER (ORDER BY (SELECT 1)), '19891231')
         AS N
   FROM master..spt_values v1,
        master..spt_values v2;

然后你可以做

DECLARE @FchRef DATE = '20110501';
DECLARE @FchCotDesde DATE = DATEADD(MONTH, -24, @FchRef);

SELECT [IdPersona],
       COUNT(DISTINCT Dates.D) AS Contributions
FROM Contributions  
JOIN Dates ON Dates.D BETWEEN fecha_ingreso AND fecha_egreso
WHERE Dates.D BETWEEN DATEADD(MONTH, -24, @FchRef) AND @FchRef
GROUP BY IdPersona
于 2013-06-12T21:25:04.260 回答
3

试试下面的。您首先需要创建一个数字函数。

create FUNCTION [dbo].[NumberTable] (@Min int, @Max int)
RETURNS @T TABLE (Number int NOT NULL PRIMARY KEY)
AS
BEGIN
INSERT @T VALUES (@Min)
WHILE @@ROWCOUNT > 0
BEGIN
INSERT @T
SELECT t.Number + (x.MaxNumber - @Min + 1)
FROM @T t
CROSS JOIN (SELECT MaxNumber = MAX(Number) FROM @T) x --Current max
WHERE
t.Number <= @Max - (x.MaxNumber - @Min + 1)
END
RETURN
END

然后我正在做的是循环工作,获取日期和日期值,并在其间插入所有日期。

 Declare @Dates table
(UserId int,
DayDate datetime
)

 create table #aux(id int identity(1,1),
        Idpersona int
        ,FechaIngreso datetime
        ,FechaEgreso  datetime
        ) 
    insert into #aux values(5690180,'1987/1/1','2012/11/30')
    insert into #aux values(5690180,'2010/1/1','2012/11/30')
    insert into #aux values(5690180,'2012/6/11','2012/11/15')
    insert into #aux values(5690180,'2012/4/12','2012/4/25')
    insert into #aux values(5690180,'2012/3/16','2012/3/30')
    insert into #aux values(5690180,'2011/6/18','2011/10/15')
    insert into #aux values(5690180,'2012/12/20','2013/1/20')
    insert into #aux values(5690180,'2012/11/21','2012/12/15')

    declare @counter int
    select @counter = 1 
 WHILE @counter <= (Select COUNT(*) from #aux)
    Begin

        declare @User int
        select @User = Idpersona from #aux where id = @counter

        declare @YearMonthDayFrom datetime
        declare @YearMonthDayTo datetime
        select @YearMonthDayFrom = FechaIngreso from #aux where id = @counter
        select @YearMonthDayTo= FechaEgreso from #aux where id = @counter

        Declare @DateDifference int
        select @DateDifference = datediff(day, @YearMonthDayFrom,  @YearMonthDayTo) 

        insert into @Dates 
        select @User,
         dateadd(day,number,  @YearMonthDayFrom) 
        from
        dbo.NumberTable(0,@DateDifference)

        select @counter = @counter + 1
    end

   select year(daydate) as PeriodGroup,
    UserId, 
    COUNT(distinct DayDate)
   from @Dates
   group by UserId,
   year(daydate)

   drop table #aux

最后,我计算不同的日子,在我的例子中,我按年份分组。

于 2013-06-12T21:40:29.117 回答