Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Previous value

Author  Topic 

noamg
Posting Yak Master

215 Posts

Posted - 2007-08-27 : 07:06:55
I have this table:

create table History(
PersonId int,
DogID int,
EndTime smalldatetime
)

insert into History( PersonId, DogID, EndTime )
select 12, 44, '2007-08-01'
union
select 12, 45, '2007-08-02'
union
select 12, 46, '2007-08-03'

I need to find who is the previous dog ?
results: PersonId, DogID, PreviousDog:
12, 46, 45
12, 45, 44

thanks
Noam


Noam Graizer

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-08-27 : 07:11:54
SELECT h.PersonID, h.DogID, (SELECT MAX(p.DogID) FROM History AS p WHERE p.DogID < h.DogID) AS PreviousDogID
FROM History AS h



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-08-27 : 07:20:43
SELECT h.PersonID, h.DogID, (SELECT TOP 1 p.DogID FROM History AS p WHERE p.EndTime < h.EndTime ORDER BY p.EndTime DESC) AS PreviousDogID
FROM History AS h



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-08-27 : 07:25:45
quote:
Originally posted by Peso

SELECT h.PersonID, h.DogID, (SELECT TOP 1 p.DogID FROM History AS p WHERE p.EndTime < h.EndTime ORDER BY p.EndTime DESC) AS PreviousDogID
FROM History AS h



E 12°55'05.25"
N 56°04'39.16"


I think top in a subquery would be costlier

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-08-27 : 09:02:28
It depends on what "previous is"...
According to ID? Use first answer
According to DATE? Use second answer.



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -