# Write a SOQL query to group Opportunities by the Year and Month of their CloseDate (CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)).

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Deloitte, PwC, ZS Associates · **Tags:** soql, scenario, date-functions, group-by

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-soql-query-to-group-opportunities-by-the-year-and-month-of-their-closedate-calendar-year-closedate

## Answer

Group by the date functions `CALENDAR_YEAR()` and `CALENDAR_MONTH()`, and alias them so they can be read from the AggregateResult.

```soql
SELECT CALENDAR_YEAR(CloseDate) yr, CALENDAR_MONTH(CloseDate) mon, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
GROUP BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)
```

---
Source: ForceChallenges · last updated 2026-10-19
