I’m trying to bring a time series sum grouped by date, week or month, depending on the total number of dates. For instance, if there is up to 30 days, group the sum by date, if there is between 31 and 90 days, group it by week and if there is more than 90 days, group it by month.
I already got the results I need with the following queries:
- Grouping by date:
SELECT
dtCreated,
FROM_DAYS(TO_DAYS(dtCreated) -MOD(TO_DAYS(dtCreated) -1, 7)) as week_beginning,
DATE(DATE_FORMAT(dtCreated, '%Y-%m-01')) AS month_beginning,
COALESCE(SUM(valToSum), 0) as soma
FROM(
SELECT
DATE(dt_created) as dtCreated,
valToSum
FROM MQV_PDV_TICKET
) as derived_table
GROUP BY dtCreated
- Grouping by week:
SELECT
dtCreated,
FROM_DAYS(TO_DAYS(dtCreated) -MOD(TO_DAYS(dtCreated) -1, 7)) as week_beginning,
DATE(DATE_FORMAT(dtCreated, '%Y-%m-01')) AS month_beginning,
COALESCE(SUM(valToSum), 0) as soma
FROM(
SELECT
DATE(dt_created) as dtCreated,
valToSum
FROM MQV_PDV_TICKET
) as derived_table
GROUP BY week_beginning
- Grouping by month:
SELECT
dtCreated,
FROM_DAYS(TO_DAYS(dtCreated) -MOD(TO_DAYS(dtCreated) -1, 7)) as week_beginning,
DATE(DATE_FORMAT(dtCreated, '%Y-%m-01')) AS month_beginning,
COALESCE(SUM(valToSum), 0) as soma
FROM(
SELECT
DATE(dt_created) as dtCreated,
valToSum
FROM MQV_PDV_TICKET
) as derived_table
GROUP BY month_beginning
All three options work just fine and bring me the right sum results with proper grouping, but I couldn’t make it group dinamically, to make it depends on the number of total days.
I already tried to use CASE WHEN
within the GROUP BY
clause, in this manner:
GROUP BY (CASE
WHEN COUNT(*) <= 30 THEN dtCreated
WHEN COUNT(*) BETWEEN 31 AND 90 THEN week_beginning
WHEN COUNT(*) > 90 THEN month_beginning
END)
but then it errors me: #1111 - invalid use of group function (GROUP)
How could I achieve this conditional grouping?
Thx in advance!
2
Answers
I would use a WITH statement, to check in a separated query the number of records, then group it accordingly the proposed conditions.
Here is one option to do it – using sample data as:
… SQL – inner query generates groupings and dates
… see it here –> https://dbfiddle.uk/tD-8peva
NOTE: you should adjust it to your context – this has been coded for sample data above