#mysql #sql #group-by #sum #rollup
#mysql #sql #группировка по #сумма #накопительный
Вопрос:
У меня есть запрос, который возвращает записи, сгруппированные по месяцам, и вычисляет СУММУ записей в таблице на основе условия:
SELECT USERS.ID AS ID, PROPERTIES.PROP_TYPE AS TIPO
,SUM(IF(MONTH(PROPERTIES.created_at) = 1, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
,SUM(IF(month(PROPERTIES.created_at) = 2, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
,SUM(IF(month(PROPERTIES.created_at) = 3, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
,SUM(IF(month(PROPERTIES.created_at) = 4, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
,SUM(IF(month(PROPERTIES.created_at) = 5, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
,SUM(IF(month(PROPERTIES.created_at) = 6, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
,SUM(IF(month(PROPERTIES.created_at) = 7, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
,SUM(IF(month(PROPERTIES.created_at) = 8, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
,SUM(IF(month(PROPERTIES.created_at) = 9, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
,SUM(IF(month(PROPERTIES.created_at) = 10, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
,SUM(IF(month(PROPERTIES.created_at) = 11, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
,SUM(IF(month(PROPERTIES.created_at) = 12, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
FROM PROPERTIES
LEFT JOIN USERS ON PROPERTIES.PROP_CAPPER_EMAIL = USERS.EMAIL_LOCAL_CRM
WHERE USERS.ID = 1283
GROUP BY PROPERTIES.PROP_TYPE, USERS.ID
Вывод этого запроса:
Что мне нужно, так это также суммировать все значения за каждый месяц и получить последнюю строку с этим результатом, ожидаемый результат:
Как я могу настроить свой запрос для получения этой последней строки с суммой значений столбцов?
С уважением!
Ответ №1:
Самый простой способ — использовать with rollup
:
GROUP BY PROPERTIES.PROP_TYPE, USERS.ID WITH ROLLUP
Однако это дает вам отдельные строки для каждой подгруппы.
В качестве альтернативы вы можете использовать CTE:
with t as (
<your query here>
)
select t.*
from t
union all
select null, null, sum(ene), sum(feb), . . .
from t;
Комментарии:
1. Спасибо @Gordo Linioff .. проблема с НАКОПЛЕНИЕМ заключается в том, что все значения суммируются правильно, но создается новая строка для всех сгруппированных столбцов «TIPO», и мне просто нужна одна дополнительная строка для всей СУММЫ
Ответ №2:
Кто-то отправил мне комментарий с подходом ОБЪЕДИНЕНИЯ, и комментарий был удален, но я прочитал его.
Итак, я считаю, что решение состоит в том, чтобы добавить это в запрос:
UNION
SELECT USERS.ID AS ID, 'Total' AS TIPO
,SUM(IF(MONTH(PROPERTIES.created_at) = 1, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
,SUM(IF(month(PROPERTIES.created_at) = 2, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
,SUM(IF(month(PROPERTIES.created_at) = 3, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
,SUM(IF(month(PROPERTIES.created_at) = 4, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
,SUM(IF(month(PROPERTIES.created_at) = 5, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
,SUM(IF(month(PROPERTIES.created_at) = 6, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
,SUM(IF(month(PROPERTIES.created_at) = 7, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
,SUM(IF(month(PROPERTIES.created_at) = 8, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
,SUM(IF(month(PROPERTIES.created_at) = 9, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
,SUM(IF(month(PROPERTIES.created_at) = 10, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
,SUM(IF(month(PROPERTIES.created_at) = 11, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
,SUM(IF(month(PROPERTIES.created_at) = 12, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
FROM PROPERTIES
LEFT JOIN USERS ON PROPERTIES.PROP_CAPPER_EMAIL = USERS.EMAIL_LOCAL_CRM
WHERE USERS.ID = 755
GROUP BY USERS.ID
С помощью этого ОБЪЕДИНЕНИЯ я показываю этот результат с разными данными строк из исходного сообщения:
Таким образом, окончательный запрос будет:
SELECT USERS.ID AS ID, PROPERTIES.PROP_TYPE AS TIPO
,SUM(IF(MONTH(PROPERTIES.created_at) = 1, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
,SUM(IF(month(PROPERTIES.created_at) = 2, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
,SUM(IF(month(PROPERTIES.created_at) = 3, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
,SUM(IF(month(PROPERTIES.created_at) = 4, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
,SUM(IF(month(PROPERTIES.created_at) = 5, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
,SUM(IF(month(PROPERTIES.created_at) = 6, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
,SUM(IF(month(PROPERTIES.created_at) = 7, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
,SUM(IF(month(PROPERTIES.created_at) = 8, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
,SUM(IF(month(PROPERTIES.created_at) = 9, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
,SUM(IF(month(PROPERTIES.created_at) = 10, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
,SUM(IF(month(PROPERTIES.created_at) = 11, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
,SUM(IF(month(PROPERTIES.created_at) = 12, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
FROM PROPERTIES
LEFT JOIN USERS ON PROPERTIES.PROP_CAPPER_EMAIL = USERS.EMAIL_LOCAL_CRM
WHERE USERS.ID = 755
GROUP BY PROPERTIES.PROP_TYPE, USERS.ID
UNION
SELECT USERS.ID AS ID, 'Total'
,SUM(IF(MONTH(PROPERTIES.created_at) = 1, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as ENE
,SUM(IF(month(PROPERTIES.created_at) = 2, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS FEB
,SUM(IF(month(PROPERTIES.created_at) = 3, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as MAR
,SUM(IF(month(PROPERTIES.created_at) = 4, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS ABR
,SUM(IF(month(PROPERTIES.created_at) = 5, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS MAY
,SUM(IF(month(PROPERTIES.created_at) = 6, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUN
,SUM(IF(month(PROPERTIES.created_at) = 7, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as JUL
,SUM(IF(month(PROPERTIES.created_at) = 8, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) AS AGO
,SUM(IF(month(PROPERTIES.created_at) = 9, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as SEP
,SUM(IF(month(PROPERTIES.created_at) = 10, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as OCT
,SUM(IF(month(PROPERTIES.created_at) = 11, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as NOV
,SUM(IF(month(PROPERTIES.created_at) = 12, PROPERTIES.PROP_EXCLUSIVE = 'Exclusiva',0)) as DIC
FROM PROPERTIES
LEFT JOIN USERS ON PROPERTIES.PROP_CAPPER_EMAIL = USERS.EMAIL_LOCAL_CRM
WHERE USERS.ID = 755
GROUP BY USERS.ID