Is there a way to group by the date portion of a datetime field in SOQL?
Asked Answered
U

2

6

Is there a way (without creating a formula datevalue(datetime) field) to aggregate a SOQL query on the date portion of a datetime field? For example, I'd like to do something like:

select datevalue(datetimeField), count(Id) from object__c group by datevalue(datetimeField)

Undoing answered 8/2, 2012 at 4:8 Comment(0)
M
14

While you can't group on a datetime field directly, there are a number of date/time functions for aggregates, so that you can group by part of the dateTime value. For example here's a query that'll show the number of account records created on each date.

select day_only(createdDate) createdonDate, 
    count(createdDate) numCreated 
    from account 
    group by day_only(createdDate) 
    order by day_only(createdDate) desc

The docs have details of all the date functions for aggregates.

day_only() returns the date part of a dateTime field.

Marielamariele answered 8/2, 2012 at 4:45 Comment(2)
That's good to know! Was also wondering if maybe using a formula field would work, though I've not tried it.Portentous
I completely missed day_only() when I read the docs. Thanks for pointing that out - it's exactly what I was looking for.Undoing
S
2

According to the DescribeSObjectResult, datetime fields are not "groupable".

Skim answered 8/2, 2012 at 4:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.