我想从按日期分组的表中获取数据,但由于我的日期列数据类型是datetime。
"select to_char(datePerformed, 'yyyy-mm-dd'), sum(sendAmount) from AppTransaction group by to_char(datePerformed, 'yyyy-mm-dd')"
因为datePerformed带有时间戳,其组包含时间戳,所以我用上面的查询
group by to_char(datePerformed, 'yyyy-mm-dd')"
我得到这样的例外,
java.lang.IllegalArgumentException: Cannot format given Object as a Date
我希望这个查询是用没有时间戳的数据对数据集进行分组,我该怎么做?
答案 0 :(得分:2)
尝试:
group by datePerformed::date
或更好
group by cast(datePerformed as date)
答案 1 :(得分:0)
Here是我使用date_trunc
和Hibernate sqlGroupProjection
的任何可能的postgres时间范围的完整解决方案。
public enum PostgresDateTrunc {
second,
minute,
hour,
day,
week,
month,
quarter,
year;
public String getPostgresGroupExpression(String dtField, String alias) {
return String.format("date_trunc('%s', %s) as %s", name(), dtField, alias);
}
}
public class GenericRepository {
public List calculateTimeGroupingStats(PostgresDateTrunc trunc, String timeGroupField, String...calculatedFields) {
Criteria criteria = createCriteria();
// adjust criteria object here
ProjectionList projection = Projections.projectionList().
add(Projections.alias(Projections.sqlGroupProjection(
trunc.getPostgresGroupExpression(timeGroupField, "timeGroupField"),
"timeGroupField", new String[]{"timeGroupField"}, new Type[]{StandardBasicTypes.DATE}),
"timeGroupField")).
add(Projections.alias(Projections.rowCount(), "count"));
for (String calculatedField : calculatedFields) {
projection.
add(Projections.alias(Projections.sum(calculatedField), calculatedField + "Sum")).
add(Projections.alias(Projections.avg(calculatedField), calculatedField + "Avg"));
}
criteria.addOrder(Order.asc("timeGroupField"));
criteria.setProjection(projection);
return criteria.list();
}
}
答案 2 :(得分:0)
我遇到了同样的问题,这种方式对我有用:
group by l.launchTime::date
我也尝试过这种方式,但不起作用:
group by cast(l.launchTime as date)
或
{{1}}