2013-01-11 150 views
0

我有以下查詢。MySQL查詢跳轉記錄

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 

問題是它在數據庫中跳轉記錄。

select FECHA_EMIS, 
    COD_VENDED, 
    sum(IMPORTE) TotalImport 
from GVA12 
group by Date(FECHA_EMIS), Year(FECHA_EMIS) 

你只在Date()Year()分組結果的COD_VENDED的價值:

問題是在這個SQL Fiddle

+0

你能否詳細說明跳樓?你什麼意思? – Taryn

+0

那麼,如果你看看SQLFiddle上的表格,你會發現1月3日有記錄。當我運行查詢時,Jan的3返回0.這種情況很多。 –

回答

1

看來,問題是你內心的子查詢複製不會是恆定的。

然後當你到您的查詢的下一部分您篩選僅記錄:

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 

SQL Fiddle with Demo

+0

只是一個問題,我試圖將IMPORTE更改爲包含在SQL小提琴中的IMPORTE_GR,而我不能。你能看到任何錯誤嗎? –

+1

它的工作原理 - http://sqlfiddle.com/#!2/253a8/10 – Taryn

+0

非常感謝! –