PDA

View Full Version : SQL query help



Mike
01-12-2010, 05:36 PM
I have a database that stores values once an hour every day. I'm wanting to query the database to give me the last (or maximum) value on the 27th of each month.

I can't filter on time, as the process didn't always run at say 11:30pm, so if not I still need to get the last one of that day (maybe 9:30pm or something), but it will always be the highest value of that day, and needs to always be the 27th of the month :)

Any ideas how to write that query?

Thanks,
Mike.

Erayd
01-12-2010, 06:17 PM
Hi Mike,

Which dialect are you after here (i.e. which RDBMS are you using)?

Also, are you wanting the maximum value that occurred: On the 27th of each month?
For the preceding calendar month, up to the 27th?
For the preceding 30 days, up to the 27th?
Since the previous 27th of a month?
Unfortunately your question is a tad ambiguous, and lacks some essential information.

Mike
01-12-2010, 06:46 PM
Unfortunately your question is a tad ambiguous :) its all there, I was just losing the plot and struggled with communicating my issue :P I want the maximum value ON the 27th of each month. I don't care about any other values on any other days :) The maximum value will also be the very last value recorded on that day.

So I want the May 27th max value, then Jun 27th max value, then Jul 27th max value

Yes I just realised I missed the RDBMS... I'm running SQL Server 2008

Hopefully that's less ambiguous :D

Mike.

Erayd
01-12-2010, 07:09 PM
I don't have a huge amount of experience with MS-SQL, but that query for PL/SQL (Oracle) would be something like:
-- Greatest value to occur on the 27th of each month
SELECT
TO_CHAR(SOME_DATE, 'MON') AS MONTH,
MAX(SOME_VAL) AS MAXVAL
FROM SOME_TABLE
WHERE
TO_CHAR(SOME_DATE, 'DD') = '27'
GROUP BY TO_CHAR(SOME_DATE, 'MON');
That will give you output that looks like this:

MONTH MAXVAL
NOV 17
DEC 16
OCT 17
SEP 15
FEB 9
JAN 16
MS-SQL will be very similar.

Edit: You may also want to sort those results, an ORDER BY on the date column is best for this (i.e. don't sort by the character representation of the month).

If you have functions available to select the day / month component of dates, this will usually be more efficient than converting the date to a formatted string. PL/SQL probably has this somewhere, but I've never needed it, and I don't have a clue what that would be.

somebody
01-12-2010, 07:12 PM
In T-SQL (for MS SQL) there's a "DAY()" function you can use instead of TO_CHAR(SOME_DATE, 'DD').

inphinity
02-12-2010, 08:20 AM
Gonna need a desc of the table the data is in to give anything specific, else assumptions must be made.

Paul.Cov
03-12-2010, 07:18 AM
So, as I understand it, these values that you are after are only ever increasing over time, and you want to get the last value recorded BEFORE the 28th.
Your solution would be to restrict the day part of the date to being <28. Then simply find the max value remaining for each month.