要获得总数,您可以使用GROUP BY WITH ROLLUP
which 应该为您提供所有日期的总数:
SELECT GVA12.FECHA_EMIS, GVA12.COD_VENDED, sum(GVA12.IMPORTE)
FROM GVA12
WHERE Month(GVA12.FECHA_EMIS)=Month(curDate())
AND Year(GVA12.FECHA_EMIS)=Year(curDate())
AND GVA12.COD_VENDED="EX"
AND GVA12.T_COMP="FAC"
GROUP BY GVA12.FECHA_EMIS WITH ROLLUP
至于不存在的返回日期,SO上有很多问题可以回答,包括以下内容。有时在 MySQL 中创建要加入的表更容易:
从日期范围生成天数
获取两个日期之间的日期列表
编辑#1:如果你有一个带有日期的表格,那么你可以使用类似于这样的东西:
SELECT Month(d.yourDateCol), Year(d.yourDateCol), g.COD_VENDED, sum(g.IMPORTE)
FROM dates d
left join GVA12 g
on Month(d.yourDateCol) = Month(GVA12.FECHA_EMIS)
and Year(d.yourDateCol) = Year(GVA12.FECHA_EMIS)
WHERE Month(g.FECHA_EMIS)=Month(curDate())
AND Year(g.FECHA_EMIS)=Year(curDate())
AND g.COD_VENDED="EX"
AND g.T_COMP="FAC"
GROUP BY Month(d.yourDateCol), Year(d.yourDateCol) WITH ROLLUP
编辑#2:没有看到您的完整表结构或一些示例数据,这里是一个正在运行的查询版本:
select month(d.dmy) Month,
year(d.dmy) Year,
coalesce(sum(g.Importe), 0) TotalImporte
from dates d
left join GVA12 g
on month(d.dmy) = month(g.FECHA_EMIS)
and year(d.dmy) = year(g.FECHA_EMIS)
group by month(d.dmy), year(d.dmy) WITH ROLLUP
请参阅SQL Fiddle with Demo。这将返回表中每个月/年的月/年,dates
即使它在GVA12
表中不存在,
编辑#3:如果您想要运行总数,而不仅仅是最终总数,那么您应该能够使用以下内容:
SET @running_total := 0;
SELECT month(Days.DMY) Month,
Year(Days.DMY) Year,
Date(Days.DMY) Date,
g.COD_VENDED,
@running_total := @running_total + Coalesce(TotalImport, 0) as TotalImport
FROM Days
left join
(
select FECHA_EMIS,
COD_VENDED,
sum(IMPORTE) TotalImport
from GVA12
group by Date(FECHA_EMIS), Year(FECHA_EMIS)
) g
on date(Days.DMY) = date(g.FECHA_EMIS)
and g.COD_VENDED='EX'
and Month(g.FECHA_EMIS)=Month(curDate())
and Year(g.FECHA_EMIS)=Year(curDate())
WHERE month(days.dmy)=Month(curDate())
请参阅带有演示的 SQL Fiddle
结果是:
| MONTH | YEAR | DATE | COD_VENDED | TOTALIMPORT |
----------------------------------------------------------------------------
| 1 | 2013 | January, 01 2013 00:00:00+0000 | (null) | 0 |
| 1 | 2013 | January, 02 2013 00:00:00+0000 | EX | 1000 |
| 1 | 2013 | January, 03 2013 00:00:00+0000 | EX | 4000 |
| 1 | 2013 | January, 04 2013 00:00:00+0000 | (null) | 4000 |
| 1 | 2013 | January, 05 2013 00:00:00+0000 | (null) | 4000 |
| 1 | 2013 | January, 06 2013 00:00:00+0000 | (null) | 4000 |
| 1 | 2013 | January, 07 2013 00:00:00+0000 | (null) | 4000 |