Author |
Topic |
ch9862
Yak Posting Veteran
76 Posts |
Posted - 2007-03-15 : 13:41:47
|
Hi,Here is my table:declare @a table (id char(2), ct int, dt datetime)insert @aselect 'A2', 18, '04/04/1980' union allselect 'A3', 18, '01/14/1983' union allselect 'A4', 18, '11/26/1982' union allselect 'A5', 18, '11/03/1989' union allselect 'A6', 18, '02/14/1986' union allselect 'A7', 18, '10/23/1981' union allselect 'A8', 18, '09/15/1983' union allselect 'A9', 20, '06/07/1985' union allselect 'AA', 20, '02/17/1988' I need to select id, dt, prev_id, prev_dt for each id. prev_dt is the highest (but lower) dt from the same table, where cert is the same as in my record. prev_id is id for that record.id dt prev_id prev_dtA2 04/04/1980 NULL NULLA3 01/14/1983 11/26/1982 A4A4 11/26/1982 10/23/1981 A7A5 11/03/1989 2/14/1986 A6A6 02/14/1986 9/15/1983 A8A7 10/23/1981 4/4/1980 A2A8 09/15/1983 1/14/1983 A3A9 06/07/1985 NULL NULLAA 02/17/1988 6/7/1985 A9 How do I do it?Any help appreciated... |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-03-15 : 13:58:47
|
[code]-- prepare sample datadeclare @a table (id char(2), ct int, dt datetime)insert @aselect 'A2', 18, '04/04/1980' union allselect 'A3', 18, '01/14/1983' union allselect 'A4', 18, '11/26/1982' union allselect 'A5', 18, '11/03/1989' union allselect 'A6', 18, '02/14/1986' union allselect 'A7', 18, '10/23/1981' union allselect 'A8', 18, '09/15/1983' union allselect 'A9', 20, '06/07/1985' union allselect 'AA', 20, '02/17/1988'-- show the expected outputSELECT a.ID, a.CT, a.DT, x.ET AS Prev_DT, b.ID AS Prev_IDFROM @a AS aINNER JOIN ( SELECT t1.DT, t1.CT, (SELECT MAX(t2.DT) FROM @a AS t2 WHERE t2.CT = t1.CT AND t2.DT < t1.DT) as ET FROM @a AS t1 ) AS x ON x.DT = a.DT AND x.CT = a.CTLEFT JOIN @a AS b ON b.DT = x.ET AND b.CT = x.CTORDER BY a.ID[/code]Peter LarssonHelsingborg, Sweden |
 |
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2007-03-15 : 14:16:12
|
you can make it just a little simpler .. basically exactly the same as Peso's, only one less self-join:select x.*, c.id as prevIDfrom( select a.id, a.ct, a.dt, (select max(dt) from @a b where a.ct = b.ct and a.dt > b.dt) as PrevDt from @a a) xleft outer join @a c on x.ct = c.ct and x.prevDt = c.dt - Jeffhttp://weblogs.sqlteam.com/JeffS |
 |
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2007-03-15 : 14:17:33
|
by the way -- GREAT job asking the question! Very clear, sample data, expected results, everything! WELL DONE! - Jeffhttp://weblogs.sqlteam.com/JeffS |
 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-03-15 : 21:12:25
|
Yes. Good job indeed. Shall bookmark this  KH |
 |
|
|
|
|