我需要以下方案的帮助。
订单表
orderId orderAmount
10001 1000.00
10002 2000.00
10003 3000.00
10004 1000.00
10005 1000.00
转移表
transferId orderId transferAmount
9001 10001 100.00
9002 10001 200.00
9003 10001 25.00
9004 10002 250.00
9005 10002 450.00
9006 10004 100.00
返回表格
returnId orderId returnAmount
8001 10001 450.00
8002 10001 50.00
8003 10002 245.00
8004 10003 100.00
需要的结果
/*include all orders from orders table, even if no transfers or returns*/
orderId transfers returns
10001 325.00 500.00 /*sum of transfers and returns per orderId from respective tables*/
10002 700.00 245.00
10003 0.00 100.00
10004 100.00 0.00
10005 0.00 0.00 /*use zero whenever no rows for orderId in respective table*/
如何在单个查询中实现上述内容?
答案 0 :(得分:1)
这很棘手。我认为最简单的方法是union all
。如果我的算术运算正确,您希望将订单金额添加到转移但不返回:
select orderId,
sum(transfers) as transfers,
sum(returns) as returns
from ((select orderId, Amount, 0 as transfers, 0 as returns
from orders o
) union all
(select orderId, 0, transferAmount, 0
from transfers
) union all
(select orderId, 0, 0, returnAmount
from transfers
)
) otr
group by orderId;
答案 1 :(得分:0)
您只需选择所有订单行即可。 对于每个订单,您子查询由OrderId链接的表。
SELECT o.orderId
, (SELECT sum(TransferAmount)
FROM Transaction t
WHERE t.OrderId = o.OrderId) 'Transaction'
, (SELECT sum(r.ReturnAmount)
FROM Result r
WHERE r.OrderId = o.OrderId) 'Return'
FROM Order o
答案 2 :(得分:0)
我会使用派生表,类似于(如果语法稍微偏离,未经测试,则道歉):
SELECT O.OrderID,COALESCE(T.Total,0) AS [Transfer Total],COALESCE(R.Total,0) AS [Return Total]
FROM Orders AS O
LEFT JOIN
(
SELECT T.OrderID,SUM(T.TransferAmount) [Total]
FROM Transfer_Table AS T
GROUP BY T.OrderID
) AS T ON O.OrderID = T.OrderID
LEFT JOIN
(
SELECT R.OrderID,SUM(R.ReturnAmount) [Total]
FROM Return_Table AS R
GROUP BY R.OrderId
) AS R ON R.OrderId = O.OrderID