我有4張桌子。
1st table has: date and revenue
2nd table has: date and cost
3rd table has: date and fees
4th table has: date and others
我正在使用以下公式計算最終收入值:
final = revenue - (cost fees others)
為了執行此操作,我在對所有這 4 個表執行左外連接時使用了合并操作。由于連接順序在左外很重要,因此當沒有收入或成本時,我會錯過費用。
Join order is revenue => cost => fees => others tables on date.
如果收入/成本缺失但費用/其他存在,如何在缺失的日期顯示這些缺失的行?
uj5u.com熱心網友回復:
我認為你需要:
SELECT `date`, COALESCE(t1.revenue, 0)
- COALESCE(t2.cost, 0)
- COALESCE(t3.fees, 0)
- COALESCE(t4.others, 0) final
FROM ( SELECT `date` FROM t1
UNION
SELECT `date` FROM t2
UNION
SELECT `date` FROM t3
UNION
SELECT `date` FROM t4 ) dates
LEFT JOIN t1 USING (`date`)
LEFT JOIN t2 USING (`date`)
LEFT JOIN t3 USING (`date`)
LEFT JOIN t4 USING (`date`)
如果每個表中的date列未定義為唯一(客戶端檢查還不夠!),那么您必須添加 GROUP BY 并在輸出運算式中的每個貨幣 (?) 列上使用 SUM()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/346614.html
上一篇:當在Swift5中點擊TableviewRow時,如何使用Xib(不是StoryBoards)在SideMenuController中設定UINavigationController以推送新的View
