SQL domanda: Come ottenere i record in base datediff da un record a
Domanda
Ok, ha ottenuto un ingannevole qui ... Se il mio dati assomiglia a questo:
Tabella 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
Come faccio a ottenere i record che sono 2 giorni di distanza l'uno dall'altro? Mia fine risultato insieme dovrebbe essere righe 1-3 e 5-6. Grazie!
Soluzione
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
Altri suggerimenti
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)
-? Che cosa questo darà
selezionare t1.id DISTINTO, t1.date_created, t2.id, t2.date_created da table1 t1, t2 table1 dove DateDiff (dd, t1.date_created, t2.date_created) = 2, t1.id! = T2.id ORDER BY t1.id;
Sarebbe questo lavoro?
select t1.id, t2.id
from table1 t1
join table1 t2
on t2.date_created - t1.date_created <= 2
Potrei suggerire utilizzando il codice di programmazione per farlo. Si desidera raccogliere gruppi di righe (gruppi separati). Non credo che si può risolvere questo utilizzando una singola query (che darebbe solo un insieme di righe di nuovo).
Se si desidera ottenere le righe che sono all'interno 'N' giorni di distanza, si può provare questo:
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;
per exmaple, come hai detto, se si desidera ottenere le righe che sono entro 2 giorni una parte, è possibile utilizzare il seguito:
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;
Spero che questo aiuta ....
Saluti, Srikrishna.
Un cursore sarà più veloce, ma qui è una query SELECT che lo farà. Si noti che per "un massimo di N" giorni di distanza invece di 2 si dovrà sostituire la tabella Due con una tabella di numeri interi da 0 a N-1 (e l'efficienza si ottiene peggio).
Devo ammettere che non è del tutto chiaro ciò che si vuole, ma io sono immagino che si desidera che le gamme di righe che contengono almeno due righe in tutto e entro il quale le file successive sono al massimo 2 giorni di distanza. Se date aumentano insieme con gli ID, questo dovrebbe funzionare.
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;