我有以下问题。
SELECT month(DMY) Month,
Year(DMY) Year,
Date(DMY) Date,
COD_VENDED,
@running_total := @running_total + Coalesce(TotalImport, 0) as TotalImport
from
(
SELECT Days.dmy,
g.COD_VENDED,
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())
) src, (SELECT @running_total := 0 AS dummy) dummy
问题是它在数据库中跳过记录。
此问题已在此SQL Fiddle
中复制答案 0 :(得分:1)
看来问题出在你的内部子查询中:
select FECHA_EMIS,
COD_VENDED,
sum(IMPORTE) TotalImport
from GVA12
group by Date(FECHA_EMIS), Year(FECHA_EMIS)
您只对Date()
和Year()
进行分组,因此COD_VENDED
的值不会保持不变。
然后,当您到达查询的下一部分时,只过滤以下记录:
g.COD_VENDED='EX'
因此,如果子查询返回的值不是EX
,那么它们就会被过滤掉。
您可能需要考虑在子查询中按COD_VENDED
进行分组:
SELECT month(DMY) Month,
Year(DMY) Year,
Date(DMY) Date,
COD_VENDED,
@running_total := @running_total + Coalesce(TotalImport, 0) as TotalImport
from
(
SELECT Days.dmy,
g.COD_VENDED,
TotalImport
FROM Days
left join
(
select FECHA_EMIS,
COD_VENDED,
sum(IMPORTE) TotalImport
from GVA12
group by Date(FECHA_EMIS), Year(FECHA_EMIS), COD_VENDED
) 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())
) src, (SELECT @running_total := 0 AS dummy) dummy