Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Help with TSQL Aggregate query using TOP

Posted on 2003-11-28
2
Medium Priority
?
340 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 375 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to shrink a transaction log file down to a reasonable size.

604 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