我一直在使用MONTH()
函数按月获取月份和分组,就像这个示例查询一样。
SELECT
t1.ano,
t1.mes,
tempo_extra,
tempo_ativo,
tempo_extra / tempo_ativo AS volume_extra
FROM
(SELECT
YEAR(`data`) AS ano,
MONTH(`data`) AS mes,
SUM(tempo) AS tempo_extra
FROM
rh.aprovacoes
WHERE
(tipo = 'BH' OR tipo = 'HE')
AND estado = 1
AND YEAR(aprovacoes.`data`) = 2016
GROUP BY MONTH(`data`)) AS t1
LEFT JOIN
(SELECT
MONTH(`data`) AS mes, SUM(ativo) AS tempo_ativo
FROM
rh.processamento
GROUP BY MONTH(`data`)) AS t2 ON t1.mes = t2.mes
ORDER BY mes DESC;
我怎样才能在上个月的23日开始月,并在当月的22日结束。
例如,4月23日开始,4月22日结束。
答案 0 :(得分:3)
只需从您的日期减去22天并添加一个月:
(`data` - interval 22 day) + interval 1 month
SQL小提琴:http://sqlfiddle.com/#!9/9eecb7d/54883
顺便提一下,无论年份如何,您的查询都会加入记录。我不认为这是理想的,所以在下面的查询中我已经纠正了这一点。
SELECT t1.ano, t1.mes, tempo_extra, tempo_ativo, tempo_extra/tempo_ativo AS volume_extra
FROM
(
SELECT
YEAR(data - interval 22 day + interval 1 month) AS ano,
MONTH(data - interval 22 day + interval 1 month) AS mes,
SUM(tempo) AS tempo_extra
FROM rh.aprovacoes
WHERE (tipo = 'BH' OR tipo = 'HE')
AND estado = 1
AND YEAR(aprovacoes.data - interval 22 day + interval 1 month) = 2016
GROUP BY
YEAR(data - interval 22 day + interval 1 month),
MONTH(data - interval 22 day + interval 1 month)
) AS t1
LEFT JOIN
(
SELECT
YEAR(data - interval 22 day + interval 1 month) AS ano,
MONTH(data - interval 22 day + interval 1 month) AS mes,
SUM(ativo) AS tempo_ativo
FROM rh.processamento
GROUP BY
YEAR(data - interval 22 day + interval 1 month),
MONTH(data - interval 22 day + interval 1 month)
) AS t2 ON t1.ano = t2.ano AND t1.mes = t2.mes
ORDER BY t1.ano DESC, t1.mes DESC;