2015-12-27 21 views
1

我有一個費用表,我試圖拉多個計算值。我從最簡單的「今天」開始。我的目標是從表中查詢我需要的數據以及相應的相關表,然後查詢具有不同日期範圍的同一父表。我有這個查詢,但todaytotal的結果是不正確的......我計算日期錯誤一些如何或缺少重要的事情?謝謝!左加入以附上日期範圍相同的表

整個事情

SELECT e.id AS exid, SUM(e.amount) AS grandtotal, e.note, e.edate, e.x1id, e.x5id, e.type, e.CreateDate, e.CreateID, e.CreateIP, 
r.name AS typename, u.fname, u.lname, ev.name as eventname, SUM(etoday.amount) AS todaytotal 
FROM 08_00_main e /* expense table */ 

LEFT JOIN 08_00_main etoday /* should only contain values with todays date */ 
ON DATE(etoday.edate) = DATE(NOW()) 

LEFT JOIN 98_00_main r /* reference table with the names of the expense types */ 
ON r.parid = 16 
AND r.tier = 3 
AND r.intid = e.type 

LEFT JOIN 01_00_main u /* user table */ 
ON u.id = e.x1id 

LEFT JOIN 05_00_main ev /* events table - expenses can be linked to an event */ 
ON ev.id = e.x5id 

WHERE e.active = 1 

GROUP BY e.type 
ORDER BY e.type 

編輯 添加我的結果/佈局更容易理解

這裏的表,因爲它坐鎮,基礎數據,查詢之前。 enter image description here

而且這裏是上面的查詢返回 enter image description here

+2

您的查詢是由每一個不包含在'聚合'功能的字段gruping,不僅喲你的專欄'類型'。這可能是你在'todaytotal'中得到的結果不同於預期的原因。爲了獲得進一步的幫助,一些數據,當前和預期的輸出將會有很大的幫助。 –

+0

謝謝。雖然我不確定我是否遵循...我嘗試將它切換一些,但仍然沒有運氣。我添加了一些圖像,以便更容易理解我在做什麼。 – b3tac0d3

回答

1

這是問題,因爲這將有效地加入電子商務每一行與etoday第4行:

LEFT JOIN 08_00_main etoday /* should only contain values with todays date */ 
ON DATE(etoday.edate) = DATE(NOW()) 

我想你想幹什麼這取而代之:

LEFT JOIN 08_00_main etoday /* should only contain values with todays date */ 
ON DATE(etoday.edate) = DATE(NOW()) AND etoday.id = e.id 
+0

你100%正確。謝謝!翻轉天才的答案。我沒有想到它通過。你今天是我的英雄。再次感謝你! – b3tac0d3