0

我有三张桌子:

  • 客户订单id, CreateDate, Status

  • 面额顺序id, DenID, OrderID

  • 面额id, amount

我想根据所有这些表创建一个视图,但应该有一个额外的列,即Total应该在那里可以计算每个订单金额的总和。

例如

  • 订单 1 总面额 3,总金额 = 250+250+250=750
  • 订单2总面额2,总金额=250+250=500

是否可以?

4

2 回答 2

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
于 2012-04-11T13:14:02.090 回答
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

使用 CTE 的演示

于 2012-04-11T13:14:48.823 回答