2

好的,这里有一个棘手的问题......如果我的数据如下所示:

表格1

ID  Date_Created 
1   1/1/2009
2   1/3/2009
3   1/5/2009
4   1/10/2009
5   1/15/2009
6   1/16/2009

如何获取相隔 2 天的记录?我的最终结果集应该是第 1-3 行和第 5-6 行。谢谢!

4

7 回答 7

1
SELECT l.*
FROM Table1 l
INNER JOIN Table1 r ON DATEDIFF(d, l.Date_Created, r.Date_Created) = 2
      AND r.Date_Created = (SELECT TOP 1 * FROM Table1 WHERE Date_Created > l.Date_Created ORDER BY Date_Create)
于 2009-07-15T21:50:31.387 回答
0

这行得通吗?

select t1.id, t2.id 
  from table1 t1 
  join table1 t2 
    on t2.date_created - t1.date_created <= 2
于 2009-07-15T21:49:33.200 回答
0

——这给了你什么?

选择 DISTINCT t1.id, t1.date_created, t2.id, t2.date_created from table1 t1, table1 t2 where datediff(dd,t1.date_created,t2.date_created) = 2 AND t1.id != t2.id ORDER BY t1 。ID;

于 2009-07-15T21:50:34.460 回答
0

我可能会建议使用编程代码来做到这一点。您想要收集行组(单独的组)。我认为您无法使用单个查询来解决此问题(这只会给您返回一组行)。

于 2009-07-15T21:51:31.790 回答
0
select distinct t1.*
from Table1 t1
inner join Table1 t2 
    on abs(cast(t1.Date_Created - t2.Date_Created as float)) between 1 and 2
于 2009-07-15T21:54:56.637 回答
0

如果你想得到相隔“N”天的行,你可以试试这个:

select t1.date_created, t2.date_created 
from table1 t1, table1 t2 
where t1.id <> t2.id and 
      t2.date_created-t1.date_created between 0 and N;

例如,正如您所说,如果您想获取 2 天内的行,您可以使用以下内容:

select t1.date_created,t2.date_created 
from table1 t1, table1.t2 
where t1.id <> t2.id and 
      t2.date_created-t1.date_created between 0 and 2;

我希望这有帮助....

问候,斯里克里希纳。

于 2009-07-16T00:06:48.273 回答
0

游标将是最快的,但这里有一个 SELECT 查询可以做到这一点。请注意,对于相隔“最多 N”天而不是 2 天,您必须将表二替换为从 0 到 N-1 的整数表(效率会变差)。

我承认这并不完全清楚你想要什么,但我猜你想要包含至少两行并且连续行最多相隔 2 天的行范围。如果日期与 ID 一起增加,这应该有效。

with Two as (
  select 0 as offset union all select 1 
), r2(ID, Date_Created_o, dr) as (
  select
    ID, Date_Created+offset,
    Date_Created + offset - dense_rank() over (
      order by Date_Created+offset
    ) from r cross join Two
)
  select
    min(ID) as start, max(ID) as finish
  from r2
  group by dr
  having min(ID) < max(ID)
  order by dr;
于 2009-07-16T04:50:55.617 回答