如何连接2个表并搜索包含SUM的2个条件

时间:2015-07-16 00:10:40

标签: sql

我有两个表,以及我正在尝试为其编写查询的两个条件。

我需要加入以下两个表:

  1. transunit
  2. 它们由两个表中的 accountID 字段连接,我还想要trans表中的 clientID

    其次我还需要将trans表中的分配字段设为'%Y',并且我需要将每个accountID的单位字段的总和用于transunit大于0.

    我可以加入这两个表,但我正在努力使用这两个条件来过滤数据。

    我想从2个表中返回的唯一列是:

    1. 帐户ID
    2. clientID的
    3. SUM(单位)
    4. 这是我到目前为止所拥有的......

      select  trans.accountID,trans.clientID from  
      inner join transUnit 
      on trans.AccountID = transUnit.accountID
      where trans.IsAllocated like '%Y%' 
      

      这会加入两个表,并使用1个条件。

      我有第二个查询,它通过accountID对transunits表中的所有记录进行求和。 1个帐户ID可以有多个单位记录。我只是在寻找SUM大于0的accountID。

      select count(*), sum(units) as Sumunits,accountid from transunit
      group by accountid 
      

      现在是棘手的部分,我如何将这两个查询连接在一起,并进行过滤,以便我只在SUM大于0时显示。

      非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

要进行聚合,您需要GROUP BY子句。 要通过聚合进行评估,您需要一个HAVING子句。 这样的事情,也许是:

select trans.accountID,trans.clientID, SUM(transunits.units)
from trans inner join transUnit on trans.AccountID = transUnit.accountID
where trans.IsAllocated like '%Y%'
GROUP BY trans.accountID,trans.clientID
HAVING SUM(transunits.units) > 0

我认为你不需要内联这个,但如果我误解了这里你怎么能这样做:

select trans.accountID,trans.clientID, q.Sumunits from trans
inner join
(select accountid, sum(units) as Sumunits,
 from transunit
 group by accountid) AS q ON trans.AccountID = q.accountID
where trans.IsAllocated like '%Y%' AND q.Sumunits > 0

答案 1 :(得分:0)

根据您的描述,您似乎想要一个having子句。一个having子句类似于where语句对组创建的group by子句,并限制返回的组:

SELECT trans.accountID, trans.clientID, SUM(units) AS Sum_of_Units
FROM trans
INNER JOIN transUnit ON trans.AccountID = transUnit.accountID 
WHERE trans.IsAllocated LIKE '%Y%'
GROUP BY trans.accountid, trans.clientid
HAVING SUM(units) > 0