简体   繁体   中英

SQL Query for Distinct Result by Most Recent Date

Dearest Professionals,

I'm in the need to get a few lists of distinct Client #'s by a few date ranges, and I'm not 100% certain how to go about it.

List 1:
I need distinct(ClientNum) with the most recent EditDate being 5 years old as of today and older.

List 2:
I need distinct(ClientNum) with most recent EditDate between 4 years old today and 5 years old today.

List 3:
I need distinct(ClientNum) with most recent EditDate between 3 years old today and 4 years old today.

Now, I have the following, and I get results, I just don't know if I'm getting what I think I should be getting.

List 1 Query:

SELECT DISTINCT(ClientNum)
FROM Table
WHERE EditDate < DATEADD(year,-5,GETDATE()) 

List 2 Query:

SELECT DISTINCT(ClientNum)
FROM Table
WHERE EditDate BETWEEN DATEADD(year,-5,GETDATE()) AND DATEADD(year,-4,GETDATE())

List 2 Query:

SELECT DISTINCT(ClientNum)
FROM Table
WHERE EditDate BETWEEN DATEADD(year,-4,GETDATE()) AND DATEADD(year,-3,GETDATE())

Is this the correct way to go about this? Or am I missing something?

Please advise.

-Nick

List 1

SELECT ClientNum, max(EditDate) as maxEditDate 
FROM Table
GROUP BY ClientNum
HAVING maxEditDate < DATEADD(year,-5,GETDATE());

List 2

SELECT ClientNum, max(EditDate) as maxEditDate 
FROM Table
GROUP BY ClientNum
HAVING maxEditDate BETWEEN DATEADD(year,-5,GETDATE()) AND DATEADD(year,-4,GETDATE());

List 3

SELECT ClientNum, max(EditDate) as maxEditDate 
FROM Table
GROUP BY ClientNum
HAVING maxEditDate BETWEEN DATEADD(year,-4,GETDATE()) AND DATEADD(year,-3,GETDATE());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM