来自2个不同表的Sql SUM

时间:2015-01-04 09:42:38

标签: sql sum

如何为总和添加两个不同的计算。

我想加上这两个。

这一个......

SELECT SUM((Price) * (InvoiceTime)) 
FROM tblTime 
WHERE OwnerId = 13749

这一个......

SELECT SUM((Price) * (Amount)) 
FROM tblMaterial 
WHERE OwnerId = 13749

5 个答案:

答案 0 :(得分:2)

您可以使用UNION ALL选择2条记录,然后使用SUM添加它们:

SELECT SUM(a.Sum1) FROM (
    SELECT SUM((Price) * (InvoiceTime)) as Sum1
    FROM tblTime 
    WHERE OwnerId = 13749
    UNION ALL
    SELECT SUM((Price) * (Amount)) 
    FROM tblMaterial 
    WHERE OwnerId = 13749
) a

答案 1 :(得分:1)

SELECT SUM((Price) * (InvoiceTime)) AS TOTAL FROM tblTime WHERE OwnerId = 13749
UNION
SELECT SUM((Price) * (Amount)) AS TOTAL FROM tblMaterial WHERE OwnerId = 13749

我认为这可能有用

答案 2 :(得分:1)

select * from
(
    SELECT SUM((Price) * (InvoiceTime)) as sum
    FROM tblTime 
    WHERE OwnerId = 13749
    union all
    SELECT SUM((Price) * (Amount)) 
    FROM tblMaterial 
    WHERE OwnerId = 13749
) tmp

答案 3 :(得分:0)

假设两个表中的价格不同,并且您想将两个数量加到一个总和

SELECT SUM((t.Price)*(t.InvoiceTime))+ SUM((m.Price)*(m.Amount)) 从tblTime t,      tblMaterial m 哪里      t.OwnerId = 13749 和t.OwnerId = m.OwnerId 小组由t.ownerId

注意:您尚未指定数据库,语法可能会有所不同。我上面指出的内容适用于Sybase。

答案 4 :(得分:0)

我会选择dotnetom的UNION ALL解决方案。只是提供另一个选项,您只需选择一个添加了两个总和的记录:

select
  coalesce
  ((
    SELECT SUM(Price * InvoiceTime) 
    FROM tblTime 
    WHERE OwnerId = 13749
  ), 0) +
  coalesce
  ((
    SELECT SUM(Price * Amount) 
    FROM tblMaterial 
    WHERE OwnerId = 13749
  ), 0);

当某些东西为NULL时,COALESCE(某事,0)会给你一个零。所以你要避免添加NULL + some_value导致NULL而不是所需的some_value。

某些dbms要求您使用包含一条记录的虚拟表。例如,对于Oracle,您必须添加FROM DUAL(在分号之前)。

这是另一种方法:构建两个和记录,然后交叉连接这些以获得一个结果记录并添加两个总和。

select t.tsum + m.msum
from
(
  SELECT COALESCE(SUM(Price * InvoiceTime), 0) AS tsum
  FROM tblTime 
  WHERE OwnerId = 13749
) t
cross join
(
  SELECT COALESCE(SUM(Price * Amount), 0) AS msum
  FROM tblMaterial 
  WHERE OwnerId = 13749
) m;