我需要知道如何在Hibernate查询结果集中获取日期范围内的所有日期。
它应该类似于SQL中的以下伪代码
从?选择“所有日期”。在TO_DATE(' date -val','format')和TO_DATE('date-val','format')之间的日期。
它可能需要一些不同的逻辑,但如果我给出一个范围,如5-2月-2011年至3月2日-2011年3月-2011年,它应该返回结果集中该范围内的所有日期.i.e
结果集=5-2月-2011年,6-2月-2011年,.2011年2月28日、3月1日至2011年、3月2日至2011年
更新:中的以下查询给出了所需的结果集
select
d.dateInRange as dateval,
eventdesc,
nvl(td.dist_ucnt, 0) as dist_ucnt
from (
select
to_date('03-NOV-2011','dd-mon-yyyy') + rownum - 1 as dateInRange
from all_objects
where rownum <= to_date('31-DEC-2011','dd-mon-yyyy') - to_date('03-NOV-2011','dd-mon-yyyy') + 1
) d
left join (
select
currentdate,
count(distinct(grauser_id)) as dist_ucnt,
eventdesc
from
txn_summ_dec
group by currentdate, eventdesc
) td on td.currentdate = d.dateInRange order by d.dateInRange asc
Resultset:
Date eventdesc dist_cnt
2011-11-03 00:00:00 null 0
and so on..
2011-11-30 00:00:00 null 0
2011-12-01 00:00:00 Save Object 182
....
2011-12-31 00:00:00 null 0发布于 2012-01-26 01:15:18
这个逻辑应该负责生成范围:
public static List<Date> dayRange(Date begin, Date end) {
if (end.before(begin)) {
throw new IllegalArgumentException("Invalid range");
}
final List<Date> range = new ArrayList<>();
final Calendar c1 = extractDate(begin);
final Calendar c2 = extractDate(end);
while (c1.before(c2)) {
range.add(c1.getTime()); // begin inclusive
c1.add(Calendar.DATE, 1);
}
range.add(c2.getTime()); // end inclusive
return range;
}
private static Calendar extractDate(Date date) {
final Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c;
}不像Joda时间那么漂亮和简洁,但能让你走。
如果您所需要的只是显示您的查询结果,对于没有结果的日期,请使用零,运行按日期分组的原始查询(没有左联接),然后填写缺少的日期。假设查询返回一个Map<String, Long>:
final DateFormat df = new SimpleDateFormat("d-MMM-yyyy", Locale.US);
final Date begin = df.parse("5-Feb-2011");
final Date end = df.parse("2-March-2011");
final List<Date> range = dayRange(begin, end);
final Map<String, Long> result = // code to execute your query
for (Date date: range) {
String key = df.format(date);
if(!result.containsKey(key)) {
result.put(key, 0l);
}
}我希望这能帮到你。
https://stackoverflow.com/questions/9012224
复制相似问题