我有一张这样的桌子(tbl1),其中“商店3”的销售金额不正确。
**date store sale**
Mar, 2013 store 1 100
Apr, 2013 store 1 80
Mar, 2013 store 2 70
Mar, 2013 store 3 125
Apr, 2013 store 3 80
正确的金额在另一个表格(tbl2)中:
**date store sale**
Mar, 2013 store 3 140
Apr, 2013 store 3 170
现在,我需要编写一个生成如下结果的查询:
**store total_sale**
store 1 180
store 2 70
store 3 310
我尝试了不同的编写CASE语句的方法,但总的来说我总是错了。我在这里简化了真正的问题,希望得到社区的帮助。谢谢!
答案 0 :(得分:2)
尝试一下,
SELECT a.Store,
COALESCE(c.TotalSale, b.TotalSale) AS TotalSale
FROM (SELECT DISTINCT Store FROM Table1) a
INNER JOIN
(
SELECT Store, SUM(sale) TotalSale
FROM Table1
GROUP BY Store
) b ON a.Store = b.Store
LEFT JOIN
(
SELECT Store, SUM(sale) TotalSale
FROM Table2
GROUP BY Store
) c ON a.Store = c.Store