473,386 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

get last 3 most recent results based on a column

Hi

I have a SQL Server 2005 database with a list of results for a variety of people over time. i would like to be able to look at any row and from that row know the last 3 results for that person

the columns are like this

date ----- person ----- result

i would like to be able to add in columns which would show

----- last result ----- last but one result ----- last but two result

i could then look at averages etc so my table (or new table) would be

date ----- person ----- result ----- last result ----- last but one result ----- last but two result

Can anyone help with a way to do this? it would need to find the previous record of the person and get their result and then go to the record of that person before that and get the result etc etc.

thanks in advance and merry christmas.
Dec 22 '09 #1
8 4710
ssnaik84
149 100+
you can get idea from this thread..

Expand|Select|Wrap|Line Numbers
  1. select top 3 * from 
  2. (select * from tablename 
  3. where person = @personid 
  4. order by date desc) as RS
  5.  
now, your new resultset RS will have last 3 results..
you can join it with your original table.
Dec 23 '09 #2
thanks for the reply but i was not clear enough in my explanation. the person column of the table has thousands of rows with hundreds of different people listsed. I need to find the last results for each and every row in the table. Obviously this won't be possible for some of the early rows in the table as there will not be previous results.

i hope that explanation makes my case clearer.
Dec 23 '09 #3
ck9663
2,878 Expert 2GB
While there's no reply yet, try this one for now...I'm sure there's a better way of doing it, but I got called at work :)

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3.  
  4. with lastrecord (personid, lastdate) 
  5. as
  6. (
  7.    select personid, max(date) as lastdate 
  8.    from transactiontable group by personid
  9. ), 
  10. last2record (personid, last2date) 
  11. as 
  12. (
  13.    select top 1 t.personid, max(t.date) as last2date 
  14.    from transactiontable t      
  15.       inner join lastrecord l on t.personid = l.personid and t.date < l.lastdate
  16.    group by personid where date    
  17. ),
  18. last3record (personid, last3date) 
  19. as 
  20. (
  21.    select t.personid, max(t.date) last3date 
  22.    from transactiontable t
  23.       inner join last2record l on t.personid = l.personid and t.date < l.last2date
  24.    group by personid where date    
  25. )
  26. select 
  27.    p.personid, l1.lastdate, l2.last2date, l3.last3date
  28. from personstable p
  29.    left join lastrecord l1 on p.personid = l1.personid
  30.    left join last2record l2 on p.personid = l2.personid
  31.    left join last3record l3 on p.personid = l3.personid
  32.  
  33.  
Happy Coding!!!


~CK
Dec 23 '09 #4
nbiswas
149 100+
Hi ssnaik84,
You cannot use Order by clause inside a subquery otherwise you will encounter the error

Msg 1033, Level 15, State 1, Line 16
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
Dec 24 '09 #5
ssnaik84
149 100+
Well nbiswas.. then use TOP... :)
isn't that simple..??

Expand|Select|Wrap|Line Numbers
  1. select top 3 * from
  2. (select top (select COUNT(*) from tablename) * 
  3. from tablename
  4. where person = @personid
  5. order by date desc) as RS
Dec 24 '09 #6
nbiswas
149 100+
Yes u r right. Now it looks fine.
Dec 24 '09 #7
only just got back to this what with christmas and all that.

thanks for all the replies. ck9663, I can't seem to get what you have done to work. i get an error saying incorrect syntax near the keyword where on line 13 which is

group by personid where date

any ideas?

also is it right that in just one of the lastrecord sub queries you use select top 1? apologies if i am way off the mark here and thanks for what you have done so far.
Jan 5 '10 #8
ck9663
2,878 Expert 2GB
Sorry about that.

Try this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. with lastrecord (personid, lastdate) 
  3. as
  4. (
  5.    select personid, max(date) as lastdate 
  6.    from transactiontable group by personid
  7. ), 
  8. last2record (personid, last2date) 
  9. as 
  10. (
  11.    select top 1 t.personid, max(t.date) as last2date 
  12.    from transactiontable t      
  13.       inner join lastrecord l on t.personid = l.personid and t.date < l.lastdate
  14.    group by personid 
  15. ),
  16. last3record (personid, last3date) 
  17. as 
  18. (
  19.    select top 1 t.personid, max(t.date) last3date 
  20.    from transactiontable t
  21.       inner join last2record l on t.personid = l.personid and t.date < l.last2date
  22.    group by personid 
  23. )
  24. select 
  25.    p.personid, l1.lastdate, l2.last2date, l3.last3date
  26. from personstable p
  27.    left join lastrecord l1 on p.personid = l1.personid
  28.    left join last2record l2 on p.personid = l2.personid
  29.    left join last3record l3 on p.personid = l3.personid
  30.  
  31.  
Happy Coding !!!

The TOP 1 is to only get he first record...

--- CK
Jan 7 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Dan Matthews | last post by:
Hey everybody, I have an 2000 Access database that stores job listings from potential employers for a school. I would like to be able to display the date on a webpage the last time the database...
4
by: Mark | last post by:
good spam subject ;). anyway, i'm alittle stumped. i'm in need of putting together a query that gets the next highest salary ( select max ( sal ) - 1?, from an emp_sal type table. another...
2
by: Astra | last post by:
Hi All I know an SQL Server timestamp seems to be as useful as rocking horse for show jumping, but I'm hoping you know a 'fudge' to get me round a problem or at least confirm that it isn't...
4
by: John A Fotheringham | last post by:
I have a table that tracks GPS records broadly speaking as follows ts DATETIME username VARCHAR(16) ... GPS data ... I want to select the most recent GPS data for each distinct user. That...
6
by: pg | last post by:
Is there any simple way to query the most recent time of "changes" made to a table? I'm accessing my database with ODBC to a remote site thru internet. I want to eliminate some DUPLICATE long...
0
by: etamp | last post by:
Etamp.net, the fast rss-reader for RSS content including weblogs and news, the fast search engine for RSS content including weblogs and news, No software download, All OS' & Browsers, IE, Netscape,...
28
by: kiqyou_vf | last post by:
I'm trying to pull data from 2 different tables and do a loop to retrieve more than one row. I'm having problems with aligning the information. Can someone lead me in the right direction? I've done...
1
by: kiqyou_vf | last post by:
Sorry, Google wouldn't let me post a reply. Here is the convo thus far: Jerry Stuckle wrote: > kiqyou_vf wrote: >> I'm trying to pull data from 2 different tables and do a loop to >> retrieve...
2
by: eloi-ribeiro.blogspot.com | last post by:
Hi, I'm having a problem with a query. I'm running Access 2000 and a table with 35000 rows. The table contains several visits to the spots with a CODE (spot code) and DATE (visit date)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.