SQL 질문 : 레코드마다 Datediff를 기반으로 한 레코드 받기

StackOverflow https://stackoverflow.com/questions/1134272

  •  16-09-2019
  •  | 
  •  

문제

좋아, 여기에 까다로운 것이있다 ... 내 데이터가 다음과 같이 보인다면 :

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)

- 이것이 당신에게 무엇을 주나요?

Datediff (dd, t1.date_created, t2.date_created, t2.date_created) = 2 및 t2.id 순서로 T1.id, t2.id, t2.date_created world t1.id, t1.date_created, t2.id, t2.date_created를 선택하십시오. .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;

Exmaple의 경우, 당신이 말했듯이, 당신이 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.

커서가 가장 빠르지 만 여기에는 선택한 쿼리가 있습니다. 2 대신 "최대 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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top