SELECT productId,SUM(quantity),SUM(totalMoney) FROM buy_contract_item GROUP BY productId
第三步:從sale_contract_item中拿到SUM(quantity),SUM(totalMoney)這兩個字段並按組 分類
SELECT productId,SUM(quantity),SUM(totalMoney) FROM sale_contract_item GROUP BY productId
第四步: 對第二步的SELECT語句進行擴充,聯結buy_contract: 獲取SUM(quantity),SUM(totalMoney)和contract_date
SELECT productId,SUM(quantity),SUM(totalMoney),contract_date FROM buy_contract_item a JOIN buy_contract b ON a.contract_id = b.id GROUP BY a.product_id;
第五步:添加where查詢條件,另外再加上別名
SELECT productId,SUM(quantity) AS buyQuantity,SUM(totalMoney) AS buyTotalMoney,b.contract_date FROM buy_contract_item a JOIN buy_contract b ON a.contract_id = b.id WHERE 1=1 and (b.contract_date >= '2015-03-13' and b.contract_date <= '2015-03-15') GROUP BY a.product_id;
第六步:寫出sale的情況和上面類似
SELECT productId,SUM(quantity) AS saleQuantity,SUM(totalMoney) AS saleTotalMoney,d.contract_date FROM buy_contract_item c JOIN buy_contract d ON c.contract_id = d.id WHERE 1=1 and (d.contract_date >= '2015-03-13' and d.contract_date <= '2015-03-15') GROUP BY c.product_id;
第一步、第五步、第六步左聯結
SELECT t.id,t.name, IFNULL(buyQuantity,0) AS buyQuantity, IFNULL(buyTotalMoney,0) AS buyTotalMoney, IFNULL(saleQuantity,0) AS saleQuantity, IFNULL(saleTotalMoney,0) AS saleTotalMoney FROM product t LEFT JOIN ( SELECT productId,SUM(quantity) AS buyQuantity,SUM(totalMoney) AS buyTotalMoney,b.contract_date FROM buy_contract_item a JOIN buy_contract b ON a.contract_id = b.id WHERE 1=1 and (b.contract_date >= '2015-03-13' and b.contract_date <= '2015-03-15') GROUP BY a.product_id; ) m ON t.id = m.productId LEFT JOIN ( SELECT productId,SUM(quantity) AS saleQuantity,SUM(totalMoney) AS saleTotalMoney,d.contract_date FROM buy_contract_item c JOIN buy_contract d ON c.contract_id = d.id WHERE 1=1 and (d.contract_date >= '2015-03-13' and d.contract_date <= '2015-03-15') GROUP BY c.product_id; ) n ON t.id = n.productId ORDER BY buyQuantity DESC, saleQuantity DESC
寫的中間可能還有錯誤,但大致思路是這樣,復雜的sql語句,可以先寫整體框架,然後在框架裡不斷的細化查詢。