我有三张桌子:
CustOrder :id, CreateDate, Status
DenominationOrder :id, DenID, OrderID
面额:id, amount
我想基于所有这些表创建一个视图,但是应该有一个额外的列,即Total
应该可以计算每个订单金额的总和。
e.g。
有可能吗?
答案 0 :(得分:2)
我尝试猜测你的表关系(以及数据,你没有提供任何样本):
SELECT co.id,
COUNT(do.DenID) AS `Total denominations`,
SUM(d.amount) AS `Total amount`
FROM CustOrder co
INNER JOIN DenominationOrder do ON co.id = do.OrderId
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY co.id
答案 1 :(得分:0)
试试这个:
SELECT o.CreateDate, COUNT(o.id), SUM(d.amount) AS 'Total Amount'
FROM CustOrder o
INNER JOIN DenominationOrder do ON o.id = do.OrderID
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY o.CreateDate
另一种方法是使用 CTE ,如下所示:
;WITH CustomersTotalOrders
AS
(
SELECT o.id, SUM(d.amount) AS 'TotalAmount'
FROM CustOrder o
INNER JOIN DenominationOrder do ON o.id = do.OrderID
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY o.id
)
SELECT o.id, COUNT(ot.id) AS 'Orders Count', ot.TotalAmount
FROM CustOrder o
INNER JOIN CustomersTotalOrders ot on o.id = ot.id
INNER JOIN DenominationOrder do ON ot.id = do.OrderID
INNER JOIN Denomination d ON do.DenId = d.id
GROUP BY o.id, ot.TotalAmount
这会给你:
id | Orders Count | Total Amount
-------+---------------+-------------
1 3 750
2 2 500