来自2个表的Sum Column Totals

时间:2015-07-30 19:45:44

标签: sql select join sum

我正在研究SQL查询/视图,我需要在每个表中对列的值求和。

所以,我有父表:LIMIT 限制有许多分配和许多扩展。 每个分配和每个扩展都有一个源实体。

分配和扩展表都有列:AR和MTM。

我需要在Allocation和Extention表中将SUM AR和MTM分成一列ARTotal和MTM Total。我需要为每个SourceEntity执行此操作。当我指定Limit OID和Source Entity OID时,我得到给定LIMIT和Source Entity的正确结果。但是,我需要获取所有Source entites,并且所有Limits Here是返回特定实体和限制的正确结果的代码:

   SELECT MAX(la.SourceEntity) as Source,
   MAX(la.limit)as Limit,
   SUM(la.ARLimit) as LAARLimit,
   SUM(la.MTMLimit) as LAMTMLimit,

   MAX(la.SourceEntity) as Source,
   SUM(le.ARLimit) as LEARLimit,
   SUM(le.MTMLimit) as LEMTMLimit,

   (Sum(la.ARLimit) + SUM(le.ARLimit)) as ARLimitTotal

    FROM  LimitAllocation la 
    INNER JOIN LimitExtension le
    on la.Limit = le.Limit

    where la.Limit = le.Limit 
    and la.SourceEntity = 'XXXXXXXXXX-4D0C-460B-8E2C-1F32732A1A20'
    and la.Limit = 'XXXXXXXXX-19f1-4a0f-81db-9598c0f58ea7'

此结果集返回给定源实体和给定限制的1记录。价值是正确的。 This is the correct result set ARTotal = LAAR + AEAR

如何在分配和扩展表中获得每个源实体的结果,它们共享相同的LIMIT OID?

1 个答案:

答案 0 :(得分:1)

试试这个并告诉我这是否是你要找的。

SELECT la.SourceEntity as Source,
   MAX(la.limit)as Limit,
   SUM(la.ARLimit) as LAARLimit,
   SUM(la.MTMLimit) as LAMTMLimit,

   la.SourceEntity as Source,
   SUM(le.ARLimit) as LEARLimit,
   SUM(le.MTMLimit) as LEMTMLimit,

   (Sum(la.ARLimit) + SUM(le.ARLimit)) as ARLimitTotal

    FROM  LimitAllocation la 
    INNER JOIN LimitExtension le
    on la.Limit = le.Limit

    where la.Limit = le.Limit 
   -- and la.SourceEntity = 'XXXXXXXXXX-4D0C-460B-8E2C-1F32732A1A20'
   -- and la.Limit = 'XXXXXXXXX-19f1-4a0f-81db-9598c0f58ea7'

GROUP BY la.SourceEntity