Skip to content
Advertisement

Group elements by month three by three

I have this Standard SQL query:

With the following output:

You can simulate the output with:

I am retreiving the entries of the last 12 months. I have already grouped and ordered them by month, but I need to also group them three by three according to the month. Moreover, as you can see in the output there are missing months, so I have created in my utils statement a truncated month array named months containing the months that should be considered. Groups need to be dynamics, so that if I am retrieving data from November 2020 to October 2021, groups should be 2020 November - January 2021, February 2021 - April 2021, May 2021 - July 2021 and August 2021 - October 2021.

This is the output of my WITH clause:

For each group of three months I need to get:

  • Name of the group: something like 2020 October - 2020 December
  • Max of ndays in the group: MAX(ndays)
  • Number of entries in that group: SUM(count)
  • Number of days elapsed in that group: to get the number of days of a month I usually use this sentence 32 - EXTRACT(DAY FROM DATETIME_ADD(DATETIME_TRUNC(DATETIME_SUB(date, INTERVAL 1 MONTH), MONTH), INTERVAL 31 DAY)), so I need the sum of that for each month of the group.

Considering all mentioned above, the output should be:

What would be the way to proceed?

Advertisement

Answer

I need the months composing each group to change according to the input … The month to start with is the first element in my months array at the utils

if to apply to sample data in your question

the output is

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement