I have a table of the following columns:
Timestamp(timestamp), data(integer), id1(integer), id2(integer)
My user will be able to give three inputs, start date (normalized to Sunday), end date (normalized to Saturday), and a list of id1.
Just to simplify my question, assuming the start date is Jan 1, 2010 assumed as Sunday, the end date is Dec 31, 2010 assumed as Saturday, and the id1 list is {100, 101, 102}, my question is
How do I com开发者_JAVA技巧pose "one" SQL string to collect max(data) from every 7-day period starting from Jan 1 to Dec 31 for every unique id1 and id2?
Also is it possible to do this with typed-safe JPA query?
Please note that I use 7-day period instead of week because there is no context of week here to avoid boundary issues like what to do with Dec 29, 20xx that falls on the first week of year 20xx + 1, etc.
Thank you very much for your answers in advance!
-Rajan
The 'WW'
date format gives the week number in the year.
SELECT id1
,id2
,TRUNC(Timestamp,'WW')
,MAX(data)
FROM mytable
WHERE Timestamp BETWEEN :start AND :end
GROUP BY id1, id2, TRUNC(Timestamp,'WW');
If the 'WW'
doesn't do it for you (boundary issues), you could take the Day number instead ('DDD'
) and divide by 7, e.g.:
TRUNC(TO_NUMBER(TO_CHAR(Timestamp,'DDD'))/7)
精彩评论