Skip to content
Advertisement

Find Recent Frequent Flyers in SQL Database

I need to find a list of frequent flyers in a database.

There are 2 important tables: Demographics and Visits.

This is what I have so far:

SELECT Demographics.[First Name], Demographics.[Last Name], Demographics.ID
FROM Demographics INNER JOIN Visits ON (Demographics.ID=Visits.ID)
WHERE Visits.[Visit Date] > #1/1/2019#
GROUP BY Demographics.[First Name], Demographics.[Last Name], Demographics.ID
HAVING COUNT(Visits.ID) >=5;

It runs and returns people who visited last year 5 or more times. However, what I ACTUALLY want is people who visited 5 or more times, and have at least 1 visit last year. I assume the answer involves an ORDER BY clause and removing the WHERE clause, but I’m not sure how to phrase it.

I am using Microsoft Access on Windows 7 (I know…) if that helps.

Thank you.

Advertisement

Answer

After thinking about it for a while, I was able to answer my own question, I believe.

Here is my solution:

SELECT Demographics.[First Name], Demographics.[Last Name], Demographics.ID
FROM Demographics INNER JOIN Visits ON (Demographics.ID=Visits.ID)
WHERE Demographics.ID IN 
(
SELECT Demographics.[First Name], Demographics.[Last Name], Demographics.ID
FROM Demographics INNER JOIN Visits ON (Demographics.ID=Visits.ID)
WHERE Visits.[Visit Date] > #1/1/2019#
GROUP BY Demographics.[First Name], Demographics.[Last Name], Demographics.ID #parts of this line are superfluous
)
GROUP BY Demographics.[First Name], Demographics.[Last Name], Demographics.ID
HAVING COUNT(Visits.ID) >=5;

The subquery checks for a visit in the past year, and the outer query checks for total number of visits.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement