第一步:从product表中拿到Id,Name两个字段(其他的字段在后面扩充)
SELECT id,name FROM product
第二步:从buy_contract_item中拿到productId,SUM(quantity),SUM(totalMoney)这两个字
段并按组分类
--productId 为了后面与product表做关联条件的
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