我有三张桌子:
客户订单:
id, CreateDate, Status
面额顺序:
id, DenID, OrderID
面额:
id, amount
我想根据所有这些表创建一个视图,但应该有一个额外的列,即Total
应该在那里可以计算每个订单金额的总和。
例如
- 订单 1 总面额 3,总金额 = 250+250+250=750
- 订单2总面额2,总金额=250+250=500
是否可以?
我试着猜测你的表格关系(还有数据,你没有提供任何样本):
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
试试这个:
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