我希望逐月使用逐个月获取每个月的数据。问题是,如果一个月没有数据,那么它会跳过月份。
这是我在MySQL中可以做的事情,还是我应该尝试在PHP中找到解决方案?我认为MySQL解决方案是最好的。
以下是我要进行的查询:
SELECT
MONTH(date) as g,
SUM(gross) AS revenue,
ABS(SUM(fee)) AS fee, COUNT(*) AS volume
FROM transactions
WHERE
date BETWEEN DATE_SUB(NOW(), INTERVAL 1 YEAR) AND NOW() and
gross > 0 and
currency = 'USD'
GROUP BY g;
答案 0 :(得分:1)
在我的一个项目中,我进行了此查询以获取' navettes'由莫伊斯' (法语月份)' @ annee'这是我的参数(C#)。你可能会受到启发......
select
max(nbNavettes) as nbNavettes,
min(Mois) as Mois
from (
select
count(*) as nbNavettes,
DATE (concat(year(s.dateLiv), '-', month(s.dateLiv), '-', '01')) AS Mois
from (
select
min(num_remorques.dateLiv) as dateLiv
from num_remorques
group by
concat(num_remorques.dateLiv,'::',num_remorques.numRemorque)
) s
where
year(s.dateLiv)=@annee
group by
year(s.dateLiv),
Month(s.dateLiv)
union
select 0 as nbNavettes,
concat(@annee,'-01-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-02-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-03-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-04-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-05-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-06-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-07-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-08-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-09-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-10-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-11-01') as Mois
union
select 0 as nbNavettes,
concat(@annee,'-12-01') as Mois
) s2
group by
s2.mois
请注意,我将monthes作为日期格式(yy-mm-01)而不是简单的int格式。 对于您的使用,您应该替换
DATE (concat(year(s.dateLiv), '-', month(s.dateLiv), '-', '01')) AS Mois
类似
month(s.dateLiv) as Mois
和
concat(@annee,'-04-01') as Mois
(和所有相同的行)
4 as Mois
答案 1 :(得分:0)
如果每个月至少有一行(即使是一个不匹配的行),那么你可以使用条件聚合来解决这个问题:
SELECT MONTH(date) as g,
SUM(CASE WHEN gross > 0 and currency = 'USD' THEN gross ELSE 0 END) AS revenue,
ABS(SUM(CASE WHEN gross > 0 and currency = 'USD' THEN fee ELSE 0 END)) AS fee,
SUM(gross > 0 and currency = 'USD') AS volume
FROM transactions
WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 1 YEAR) AND NOW() and
GROUP BY g;
这不能保证有效。但有时这是解决此类问题的简单方法。
如果没有,那么您需要在具有所需月份的表格上使用LEFT JOIN
。在PHP中完成工作可能更简单。