I’m trying to get the maximum date for an area_id from a ‘review’ table and return only those area_id’s that have a max date_finished greater than one year (from today’s date). The table structure is something like this
1) the 'review' table can have one or more reviews (multiple date_finished) for
each area_id
2) each region_id can have one or more area_ids
OBJECTIVE: Return the number of reviews per region_id with a date_finished greater than a year
Sample data:
region_id area_id date_finished
abc area_3 '01-01-2010 12:00:00 AM'
abc area_3 '06-01-2009 12:00:00 AM'
abc area_3 '02-01-2008 12:00:00 AM'
The expected result above should be return region abc and count should be 1 (because the max date_finished is january 1, 2010 and that is greater than a year from today’s date (2013)
The sql I have is below. For some reason it returns all of the dates I have described above. Instead of returning the max date it returns 3 dates. I’m using SQL Server 2008. Thanks!
select count(*)
from review group by area_id
having datediff(day,max(date_finished), getdate()) > 365
I think you can get what you want through two levels of aggregation, first by region and area, the second by region: