2012-06-20 75 views
0

我試圖獲得calc.transport的總數 表3_product_folder包含重複的值('folder_id'列),我該如何防止搞亂SUM? 我試過DISTINCT沒有成功。使用SUM和JOIN獲取唯一值

有什麼建議嗎?

SELECT 
SUM(calc.transport) AS transport 
FROM 0_calculatie_id AS calc 
LEFT JOIN 0_calculatie_inh_id AS id 
ON id.calculatie_id = calc.id 
LEFT JOIN 3_product_folder AS fld_id 
ON fld_id.product_id = id.id 
LEFT JOIN 4_folder_dossier AS fld 
ON fld.product_folder_id = fld_id.folder_id 
LEFT JOIN 10_factuur_inh AS fac_inh 
ON fac_inh.folder_id = fld.id 
LEFT JOIN 9_factuur_id AS fac 
ON fac.id = fac_inh.factuur_id 
WHERE YEAR(fac.datum_verstuurd) = ".$row['jaar']." AND MONTH(fac.datum_verstuurd) = ".$row_mth2['maand']." 

我已經試過這種嵌套查詢,但並非所有的項目計算,則:

SELECT 
SUM(temp.transport) AS transport 
FROM 
(SELECT DISTINCT 
calc.transport, 
fld_id.folder_id 
FROM 0_calculatie_id AS calc 
LEFT JOIN 0_calculatie_inh_id AS id 
ON id.calculatie_id = calc.id 
LEFT JOIN 3_product_folder AS fld_id 
ON fld_id.product_id = id.id 
LEFT JOIN 4_folder_dossier AS fld 
ON fld.product_folder_id = fld_id.folder_id 
LEFT JOIN 10_factuur_inh AS fac_inh 
ON fac_inh.folder_id = fld.id 
LEFT JOIN 9_factuur_id AS fac 
ON fac.id = fac_inh.factuur_id 
WHERE YEAR(fac.datum_verstuurd) = 2012 AND MONTH(fac.datum_verstuurd) = 7) AS temp 
+0

您已嘗試(SELECT DISTINCT ...)'嵌套選擇像'SELECT SUM(...)? –

+0

我對帖子中添加了評論 – Muiter

回答

1

什麼表的結構?

你沒有分組的SQL語句:

WHERE YEAR(fac.datum_verstuurd) = ".$row['jaar']." AND MONTH(fac.datum_verstuurd) = ".$row_mth2['maand']." 
GROUP BY fld_id.product_id 
+0

這會給我一個按月份和年份按項目和noy分組的結果 – Muiter

+0

將條件移到HAVING語句http://dev.mysql.com/doc/refman/5.0/en/group逐隱藏columns.html –