2017-02-02 226 views
0

我有以下查詢GROUP BY列總和忽略

SELECT YEAR(T.date), MONTH(T.date), T.production, T.lineID, SUM(rework + scrap) 
FROM 
    (SELECT MAX(positionID), date, production, lineID 
    FROM productionPerPosition 
    WHERE lineID = 2 
    AND date BETWEEN '2017-01-01' AND '2017-01-31' 
    GROUP BY date) AS T 
INNER JOIN linePosition lp ON lp.lineID = T.lineID 
INNER JOIN fttErrorType fet ON fet.positionID = lp.positionID 
INNER JOIN fttData fd ON fd.errorID = fet.errorID 
         AND fd.date = T.date 
GROUP BY YEAR(T.date), MONTH(T.date) 

這給這個結果現在

enter image description here

,我想組這些結果由一年月獲得生產總額和最後一欄的總和。我試過這個查詢

SELECT YEAR(T.date), MONTH(T.date), SUM(T.production), T.lineID, SUM(rework + scrap) 
FROM 
    (SELECT MAX(positionID), date, production, lineID 
    FROM productionPerPosition 
    WHERE lineID = 2 
    AND date BETWEEN '2017-01-01' AND '2017-01-31' 
    GROUP BY date) AS T 
INNER JOIN linePosition lp ON lp.lineID = T.lineID 
INNER JOIN fttErrorType fet ON fet.positionID = lp.positionID 
INNER JOIN fttData fd ON fd.errorID = fet.errorID 
         AND fd.date = T.date 
GROUP BY YEAR(T.date), MONTH(T.date) 

這給了我

enter image description here

這裏生產總和是錯誤的!看起來第一個查詢中第7行的GROUP BY被忽略。

任何想法我怎麼能得到需要的結果?

編輯:在內部SELECT我有幾個不同的位置(positionID)獨立生產,但我只用生產從具有最高positionID

+0

以及您使用的是非標準組通過查詢(如舊版本的mysql所允許的)。這有時會給出更奇怪的結果 – e4c5

+0

分組的標準方式是什麼? – justRadojko

+1

太長的評論:https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html – e4c5

回答

0

已e4c5評論解釋的位置,你要添加的所有未聚集字段添加到您的GROUP BY。我在內部SELECT使其在主選擇:

SELECT YEAR(T.date), MONTH(T.date), SUM(T.production), T.lineID, SUM(rework + scrap) 
FROM 
    (SELECT MAX(positionID), date, production, lineID 
    FROM productionPerPosition 
    WHERE lineID = 2 
    AND date BETWEEN '2017-01-01' AND '2017-01-31' 
    GROUP BY date, production, lineID) AS T 
INNER JOIN linePosition lp ON lp.lineID = T.lineID 
INNER JOIN fttErrorType fet ON fet.positionID = lp.positionID 
INNER JOIN fttData fd ON fd.errorID = fet.errorID 
         AND fd.date = T.date 
GROUP BY YEAR(T.date), MONTH(T.date), T.lineID 
+0

我仍然得到相同的結果與這個修改後的查詢 – justRadojko

+0

你的返工在哪裏並在子查詢中的字段?我認爲你必須揭露他們並將他們分組。 – kiks73

+0

他們只出現在fttData表 – justRadojko

0

集團已丟失的分組就是爲什麼它是導致一些意想不到的結果列

SELECT YEAR(T.date), MONTH(T.date), SUM(T.production), T.lineID, SUM(rework + scrap) 
    FROM 
     (SELECT MAX(positionID), date, production, lineID 
     FROM productionPerPosition 
     WHERE lineID = 2 
     AND date BETWEEN '2017-01-01' AND '2017-01-31' 
     GROUP BY date, production, lineID) AS T 
    INNER JOIN linePosition lp ON lp.lineID = T.lineID 
    INNER JOIN fttErrorType fet ON fet.positionID = lp.positionID 
    INNER JOIN fttData fd ON fd.errorID = fet.errorID 
          AND fd.date = T.date 
    GROUP BY YEAR(T.date), MONTH(T.date), T.lineID 
+0

仍然得到相同的結果 – justRadojko