Click here to Skip to main content
15,908,444 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have two tables, 'users' and 'user_grading'. in 'users' tables i had user name and other details and 'userid' is the primary key. in 'user_grading' table i had grading of all users and the year of which the grading is, 'gradingid' is the primary key and 'userid' is the foreign key. now i need to get the last 3 year grading of each user with its name which is stored in other table. please help me how to do this in sql server 2005. the table details are as follows...

users:
userid int PK
User_Name text

user_grading:
gradingid int PK
userid int FK
grading text
year int

...........
and what i want is some what like this

UserName Year Grading
sam 2009 good
sam 2010 avg
sam 2011 good
john 2007 good
john 2009 avg
john 2010 good
... and so on
please tell me what to do
Posted

If I understood correctly, the last 3 gradings are not necessarily from last 3 years. In your example you have
john 2007 good
john 2009 avg
john 2010 good

So John doesn't have any grading for the year 2008.

If this is the problem, you can try something like:
SQL
SELECT *
FROM users u,
     user_grading ug
where u.userid = ug.userid
and   3 <= (select count(*)
            from user_grading ug2
            where ug2.userid = ug.userid
            and ug2.year > ug.year)
 
Share this answer
 
Comments
Espen Harlinn 17-Aug-11 18:33pm    
Good reply, my 5
Wendelius 18-Aug-11 0:28am    
Thanks :)
I'm not a sql expert by any means, but this might work...

SQL
select top 3 
       u.user_name
       ,g.year       
       ,g.name
from [users] u
inner join user_grading g 
on u.userid = g.userid
order by g.year desc


EDIT ==================

Okay then, try this:

SQL
select u.user_name
       ,g.year
       ,g.name
from [users] u
inner join user_grading g
on u.userid = g.userid
where g.year >= DATEPART(year, GETDATE()) - 2
order by u.user_name, g.year desc


Have you ever considered actually trying stuff yourself?
 
Share this answer
 
v4
Try:
SQL
SELECT u.User_name AS UserName, g.year AS Year, g.grading As Grading 
   FROM users AS u 
   JOIN user_grading AS g 
      ON u.userid=g.userid 
   WHERE g.Year>=DATEPART(year, GETDATE()) - 2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900