【问题标题】:Summing Detail records in Master Detail SQL Statement汇总 Master Detail SQL 语句中的 Detail 记录
【发布时间】:2012-03-06 23:42:33
【问题描述】:

我有两张桌子

Master  
Detail

在 Master & Detail 表中,我有一个 Amount 字段

我需要获取 Amount in Detail 的 SUM 并从 Master 中的 Amount 中减去它并显示在“Current_Amount”中

“Current_Amount”应该等于“Master.Amount” - “Detail.Amount”的总和

【问题讨论】:

  • 是否有一列链接了这两个表?..

标签: sql sum inner-join


【解决方案1】:

如果没有两张表的大量详细信息,这将为您提供总数:

SELECT (Max(M.Amount) - SUM(D.Amount)) as CurrentAmount
FROM Master M
INNER JOIN Detail D
    ON M.ID = D.ID

那么,如果你想要包含 Master Id:

SELECT M.ID, (Max(M.Amount) - SUM(D.Amount)) as CurrentAmount
FROM Master M
INNER JOIN Detail D
    ON M.ID = D.ID
GROUP BY M.ID

【讨论】:

    【解决方案2】:

    试试:

    select m.ID, max(m.Amount) - sum(d.Ammount) Current_Amount
    from Master m
    left join Detail D on m.ID = d.Master_ID
    group by m.ID
    

    - 假设 Master 主键 ID 作为 Master_ID 存储在 Detail 上。

    【讨论】:

      【解决方案3】:

      这是对连接条件的假设,因为您没有指定...

      SELECT     Master.ID,
                 (MAX(Master.Amount) - ISNULL(SUM(Detail.Amount), 0)) AS Current_Amount
      FROM       Master
      LEFT JOIN  Detail ON Detail.MasterID = Master.ID
      GROUP BY   Master.ID
      

      注意: MAX(Master.Amount) 只是消除了在 group by 子句中指定 Master.Amount 的需要。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-07
        • 2011-12-23
        • 1970-01-01
        相关资源
        最近更新 更多