题
好,我知道一个棘手这里......如果我的数据是这样的:
表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。谢谢!
解决方案
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
其他提示
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)
- ?是什么让你
选择DISTINCT t1.id,t1.date_created,t2.id,从表1 T1 t2.date_created,表1 T 2,其中DATEDIFF(DD,t1.date_created,t2.date_created)= 2且t1.id!= t2.id ORDER BY t1.id;
将这工作?
select t1.id, t2.id
from table1 t1
join table1 t2
on t2.date_created - t1.date_created <= 2
我可能会建议使用编程代码来做到这一点。要收集行(独立团)的群体。我不认为你可以在此使用单个查询(这会给你只是一组行背面)解决。
如果你想获得其中不到“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;
我希望这有助于....
此致 Srikrishna。
一个光标将是最快的,但这里是一个SELECT查询,将这样做。请注意,“达N”相隔几天而不是2你必须从0与整数的表来代替表2的N-1(和效率会变得更糟)。
我承认它不是完全清楚自己想要什么,但我想你想的是包含在所有和其内至少两行的连续行是最多2相隔几天行的范围。如果日期与标识而增加,这应该工作。
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;
不隶属于 StackOverflow