如何计算select语句列中其他表的总值

时间:2012-04-11 13:08:59

标签: sql database

我有三张桌子:

  • CustOrder id, CreateDate, Status

  • DenominationOrder id, DenID, OrderID

  • 面额id, amount

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

e.g。

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

有可能吗?

2 个答案:

答案 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

DEMO

另一种方法是使用 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

DEMO using CTE