简体   繁体   English

Oracle / sql / jpa - 对于年度跨度表,如何从每7天选择包含最大数据(一列)的行?

[英]Oracle/sql/jpa - With a year-span table, how do I select rows with max data (a column) from every 7 days?

I have a table of the following columns: 我有一个包含以下列的表:

Timestamp(timestamp), data(integer), id1(integer), id2(integer) 时间戳(时间戳),数据(整数),id1(整数),id2(整数)

My user will be able to give three inputs, start date (normalized to Sunday), end date (normalized to Saturday), and a list of id1. 我的用户将能够提供三个输入,开始日期(标准化为星期日),结束日期(标准化为星期六)和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 为了简化我的问题,假设开始日期是2010年1月1日假定为星期日,结束日期是2010年12月31日假设为星期六,id1列表是{100,101,102},我的问题是

How do I compose "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? 对于每个唯一的id1和id2,如何从1月1日到12月31日的每7天收集“一个”SQL字符串来收集最大值(数据)?

Also is it possible to do this with typed-safe JPA query? 也可以使用类型安全的JPA查询来执行此操作吗?

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. 请注意,我使用的是7天而不是一周,因为这里没有周的上下文来避免边界问题,例如12月29日的20xx,20xx + 1的第一周,等等。

Thank you very much for your answers in advance! 非常感谢您提前的答案!

-Rajan -Rajan

The 'WW' date format gives the week number in the year. 'WW'日期格式给出了一年中的周数。

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, eg: 如果'WW'没有为你做(边界问题),你可以取代Day编号( 'DDD' )并除以7,例如:

TRUNC(TO_NUMBER(TO_CHAR(Timestamp,'DDD'))/7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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