表示例:
branch
----------------------------------
branchID | branchName | brMgrName|
----------------------------------
| 1 | a |Tom |
| 2 | b |Jeff |
| 3 | c |Lin |
----------------------------------
order
----------------------
orderID | branchID |
----------------------
| 1 | 2 |
| 2 | 2 |
| 3 | 3 |
----------------------
payment
--------------------------------
paymentID | orderID | p-amount |
--------------------------------
| 1 | 1 | 50.00 |
| 2 | 2 | 126.00 |
| 3 | 3 | 50.00 |
--------------------------------
我想要的输出是
-------------------------------------------
| branchName | brMgrName | Total Amount |
-------------------------------------------
| a | Tom | 0.00 |
| b | Jeff | 252.00 |
| c | Lin | 50.00 |
-------------------------------------------
我试图确定如何在3个不同的表中总结每个分支的金额。
在输出中:
- branchName' a'没有来自订单表的任何价值,
- branchName' b'总结了paymentID 1& 2,与之相同
- branchName' c'
通过加入分支表和付款表,我已成功返回branchName和Total Amount:
SELECT `order`.branchID, sum(`p-amount`)
FROM `order`
JOIN payment
ON `order`.orderID = payment.orderID
GROUP BY branchID
但是当我尝试下面的代码时,它返回错误的值,只选择了1行。
SELECT branchName, brMgrName, sum(`p-amount`)
FROM branch, payment
JOIN (SELECT `order`.branchID, sum(`p-amount`)
FROM `order`
JOIN payment
ON `order`.orderID = payment.orderID
GROUP BY branchID) b
ON b.branchID = branchID;
非常感谢任何帮助。
答案 0 :(得分:1)
试试这个:
SELECT b.branchName, brMgrName, sum(p.`p-amount`)
FROM branch b
LEFT JOIN `order` o
ON b.branchID = o.branchID
LEFT JOIN payment p
ON o.orderID = p.orderID
GROUP BY b.branchName, brMgrName
ORDER BY 3 -- third column on select list
答案 1 :(得分:1)
试试这个吗?
SELECT `branch`.`branchID`, `branch`.`branchName`, `branch`.`brMgrName`, SUM(`payment`.`p-amount`)
FROM `branch`
JOIN `order` ON `branch`.`branchID` = `order`.`branchID`
JOIN `payment` ON `order`.`orderID` = `payment`.`orderID`
GROUP BY `branch`.`branchID`
答案 2 :(得分:1)
SELECT b.branchName,b.brMgrName,
ISNULL( (SELECT sum(p.pamount) FROM dbo.payment p
WHERE p.orderID IN (SELECT o.orderid FROM dbo.[order] o
WHERE o.branchID=b. branchID)),0) FROM dbo.branch b
使用Subquery