仅获取在结束日期之前具有多个开始日期的ID

时间:2015-08-27 14:09:35

标签: sql-server tsql cursor

我做了这个选择并得到了这些值。我只需要获得那些由于某种原因在结束日期之前有两次或更多开始日期的那些(例如:第一个,如果你看前两行)

     id       id        Start Date                End Date
    33730   33730   01/02/2012 12:00:00 AM  13/11/2012 12:00:00 AM
    33730   33730   26/10/2012 12:00:00 AM  13/11/2012 12:00:00 AM
    33732   33732   01/02/2012 12:00:00 AM  01/10/2013 12:00:00 AM
    33732   33732   05/08/2013 12:00:00 AM  01/10/2013 12:00:00 AM
    33744   33744   02/02/2012 12:00:00 AM  12/04/2012 12:00:00 AM
    33744   33744   13/03/2012 12:00:00 AM  12/04/2012 12:00:00 AM

这是我的初步查询

   select ENTRADA.nro_referencia as id1, SALIDA.NRO_REFERENCIA as id2, ENTRADA.FECHA_ENTRADA as Start_Date, SALIDA.FECHA_SALIDA as End_Date
   FROM ENTRADA LEFT JOIN SALIDA on ENTRADA.NRO_REFERENCIA = SALIDA.NRO_REFERENCIA
    where FECHA_ENTRADA < '1/1/2014' AND
   ENTRADA.NRO_REFERENCIA in 
   (select dbo.ENTRADA.NRO_REFERENCIA from ENTRADA where FECHA_ENTRADA < FECHA_SALIDA group by dbo.ENTRADA.NRO_REFERENCIA having count(*) > 1)
   order by dbo.ENTRADA.NRO_REFERENCIA

3 个答案:

答案 0 :(得分:0)

这将为您提供一个ID列表,其中包含结束日期之前的开始日期至少两次:

SELECT id
  FROM myTable
  WHERE StartDate < EndDate
  GROUP BY id
  HAVING COUNT(*) > 2

您可以将其与IN子句一起使用来过滤主查询:

SELECT id, StartDate, EndDate
FROM myTable
WHERE id IN (
  SELECT id
    FROM myTable
    WHERE StartDate < EndDate
    GROUP BY id
    HAVING COUNT(*) > 2)

答案 1 :(得分:0)

这将为您提供记录,其中相同的ID在第一个结束日期之前有两个单独的开始日期,但不确定这是否是您希望输出组织的方式:

with cte as (
select row_number over (partition by ENTRADA.nro_referencia order by SALIDA.FECHA_SALIDA ) as rn,
ENTRADA.nro_referencia as id1, SALIDA.NRO_REFERENCIA as id2,
ENTRADA.FECHA_ENTRADA as Start_Date, SALIDA.FECHA_SALIDA as End_Date
FROM ENTRADA LEFT JOIN SALIDA on ENTRADA.NRO_REFERENCIA = SALIDA.NRO_REFERENCIA)

select a.id1,a.Start_Date,b.End_Date
from cte a
inner join cte b
on a.id1 = b.id1
and a.Start_Date< b.End_Date
and a.rn > b.rn

答案 2 :(得分:0)

您可以使用ROW_NUMBER来识别重复项,即具有相同idEnd_Date但多于一个Start_Date的记录。然后将您的初始查询放在子查询中,并使用ROW_NUMBER计算的字段,以过滤掉重复项:

SELECT id1, id2, Start_Date, End_Date
FROM (    
SELECT ENTRADA.NRO_REFERENCIA as id1, SALIDA.NRO_REFERENCIA as id2, 
       ENTRADA.FECHA_ENTRADA as Start_Date, SALIDA.FECHA_SALIDA as End_Date,
       ROW_NUMBER() OVER (PARTITION BY ENTRADA.NRO_REFERENCIA, SALIDA.FECHA_SALIDA 
                          ORDER BY ENTRADA.FECHA_ENTRADA) AS rn
FROM ENTRADA 
LEFT JOIN SALIDA on ENTRADA.NRO_REFERENCIA = SALIDA.NRO_REFERENCIA
WHERE FECHA_ENTRADA < '1/1/2014' AND ENTRADA.NRO_REFERENCIA in 
   (SELECT dbo.ENTRADA.NRO_REFERENCIA 
    FROM ENTRADA 
    WHERE FECHA_ENTRADA < FECHA_SALIDA 
    GROUP BY dbo.ENTRADA.NRO_REFERENCIA 
    HAVING COUNT(*) > 1) ) AS t
WHERE t.rn = 1    
ORDER BY id1

如果您想保留包含最新 End_Date的记录,只需在ORDER BY ENTRADA.FECHA_ENTRADA子句中将ORDER BY ENTRADA.FECHA_ENTRADA DESC更改为OVER即可。