查找子 table 列的 SUM 小于父子总列

Find SUM of child table column is less than parent child total column

4 小时以来,我一直在尝试编写一个 SQL 查询,如果子 table 横断面(数量)超过父 table 中定义的最大限制,该查询可以显示记录。 TB1 是父 table,而 TB2 是子 table。这是查询:

SELECT 
    SUM(b.amount) AS sum_transection,
    a.amount AS total,
    sum_transection - total AS diff
FROM 
    dbo.tb1 a INNER JOIN  dbo.tb2 b ON
    a.grp = b.grp AND a.head = b.head 
WHERE
     sum_transection - total >0

我认为您应该根据您的要求使用 Group by,而不能在您的情况下使用 Alias in Where 条件。 (我正在使用 SQL 服务器,不确定您是否有不同的工具) 我做了一些这样的改变

SELECT 
    SUM(b.amount) AS sum_transection,
    a.amount AS total,
    SUM(b.amount) - a.amount AS diff
FROM 
    dbo.tb1 a INNER JOIN  dbo.tb2 b ON
    a.grp = b.grp AND a.head = b.head 
GROUP BY a.grp, a.amount
having SUM(b.amount) - a.amount >0