简体   繁体   中英

How to group by date without time-stamp in hibernate query language?

I want to get data from a table that is grouped by date, but since my date column data type is datetime.

"select to_char(datePerformed, 'yyyy-mm-dd'), sum(sendAmount) from AppTransaction group by to_char(datePerformed, 'yyyy-mm-dd')"

since datePerformed with time-stamp, its group with including the time stamp, so i have used above query with

group by to_char(datePerformed, 'yyyy-mm-dd')"

I'm getting an exception like this,

java.lang.IllegalArgumentException: Cannot format given Object as a Date

I want this query to be group my data set with data without time-stamp, how can I do it?

try :

group by datePerformed::date

or better

group by cast(datePerformed as date)

Here is my complete solution with any possible postgres time range using date_trunc and Hibernate sqlGroupProjection .

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();
    }

}

I had the same problem, and this way works for me:

SELECT to_char(l.launchTime, 'mm-dd-yyyy'), count(l) 
  FROM Launch l 
 GROUP BY to_char(l.launchTime, 'mm-dd-yyyy')

I tried this way too, but doesn't work:

group by l.launchTime::date

or

group by cast(l.launchTime as date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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