Wednesday, March 28, 2012

Is this query possible?

Hi folks.

So I have a table which stores the following information:

a recordID (PK)
a regionID
a month (in text; such as "January 2005")
and other fields which probrably aren't important to know for this question.

The table can have more than one record for each region and month in question. The problem is for the report I want to pull up ONLY the last record for each region for the month. I got around this by doing a seperate query for each region (5 total). Now I have to do the totals for all regions combined. I could do this math using the array but I was wondering if I was able to do a query to do it for me.

So, I want to query the database and retreive 1 record. That record would contain aggragate data from each of the regions (the last record for each region and the month in question).

I might not be asking the right question, which aludes that I might not understand the problem or capabilities of SQL (newbie).

Thanks,
Douglas.If I am following you correctly, I'd try something like this:


SELECT
myTable.regionID,
myTable.month
FROM
myTable
INNER JOIN
(
SELECT
regionID,
max(recordID) AS recordID
FROM
myTable
GROUP BY
regionID
) AS SQ ON myTable.recordID = SQ.recordID

Terri|||That was perfect. Thank you.
I forgot to say thanks. Actually, I didn't even know that was an option. I use this sort of stuff a ton now.
Douglas.

No comments:

Post a Comment