Solved

Help with TSQL Aggregate query using TOP

Posted on 2003-11-28
2
332 Views
Last Modified: 2006-11-17
I have two tables, Person (id int, name varchar()) and Appointment(date datetime, personid int, notes varchar())
personid from the Appointment table reference is from the Person table.

The Person table contains is and name of some people. The Appoinment table contains the date the each person was visited. There can be many entries in the Appoinment table for each person. i.e. They is a record of many visits for each person.

I need a query that gives the 5 most recent visits for ALL the people in the Person table, not just one person. So I need a query that for each person in the person table will return the 5 (or however many) most recent vists. i.e.(date <= today).
0
Comment
Question by:deem1
2 Comments
 
LVL 6

Expert Comment

by:lausz
ID: 9837724
Can you post same sample with data and what do you want as ansewer ?
0
 
LVL 10

Accepted Solution

by:
RichardCorrie earned 125 total points
ID: 9837760

for convenience add an Identity field to Appoint ment table (AppointmentID) then
try
Select
   P.PersonID,
  P.Name,
  A.Date,
A.Notes
from
 Person P
inner join
Appointment A
on
P.PersonID = A.PersonID
where
A.Appointmentid in(Select TOP 5 AppointmentID from Appointment AP Where AP.PersonID = A.PersonID and AP.Date<=getdate() order by AP.Date DESC)

Richard
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now