三表查詢、統計

一張訂單表

estimate_id title

一張銷售表

sell_id estimate_id no sprice snum

一張採購表

buy_id estimate_id no bprice bnum

一個訂單對應多個銷售和採購(estimate_id),一個銷售對應多個採購(no)

查詢的結果:

title   scount    bcount 

XX     10.00        5.00

BB                               (注:這種情況可能是隻有訂單,還沒有銷售和採購)

AA    100.00     45.00

 ..         ....             .....

SQL語句:

SELECT e. * , s.scount, b.bcount 
FROM tb_estimate AS e
LEFT JOIN (
	SELECT SUM( sprice * snum ) AS scount, estimate_id
	FROM tb_sell
	WHERE deleted =0
	GROUP BY estimate_id
) AS s ON e.estimate_id = s.estimate_id
LEFT JOIN (
	SELECT SUM( bprice * bnum ) AS bcount, estimate_id
	FROM tb_buy
	WHERE deleted =0
	GROUP BY estimate_id
) AS b ON b.estimate_id = e.estimate_id
WHERE e.deleted =0
ORDER BY updated DESC


發佈了47 篇原創文章 · 獲贊 25 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章