【问题标题】:How do I join 2 tables and search for 2 conditions including a SUM如何加入 2 个表并搜索 2 个条件,包括 SUM
【发布时间】:2015-10-05 06:10:01
【问题描述】:

我有两个表和两个要编写查询的条件。

我需要加入以下两个表:

  1. 翻译
  2. 跨单位

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

其次,我还需要 trans 表中的字段 allocated 为 '%Y',并且我需要 transunit 中每个 accountID 的 units 字段的总和大于0。

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

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

  1. 帐户ID
  2. 客户端ID
  3. 总和(单位)

这是我目前所拥有的......

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 时显示。

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 请显示示例表数据和预期输出。
  • 要过滤聚合,having clause 就是你想要的。

标签: sql


【解决方案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

【讨论】:

  • 我尝试了前一个查询,效果很好。干杯
【解决方案2】:

根据您的描述,听起来您想要一个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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 2021-11-24
    • 2022-12-18
    相关资源
    最近更新 更多