SQL查询第二个和列平方结果

时间:2014-05-15 09:24:48

标签: sql sql-server-2008 group-by sum

如果我单独运行2个查询,我会得到这样的结果..

 select A.ACTNUMST, sum(B.EXTDCOST) as [IV Total]
 from GL00105 A
 INNER JOIN SEE30303 B on A.ACTINDX = B.IVIVINDX
 group by A.ACTNUMST

 Results -
 Account No      IV Total
 2101-00-137     2033.60
 4101-00-137     83765.86
 6101-00-137     301984.23

第二次查询

 select A.ACTNUMST as [Account No], SUM(C.PERDBLNC) as [GL Total]
 from GL00105 A
 LEFT JOIN GL10110 C on A.ACTINDX = C.ACTINDX
 group by A.ACTNUMST

 Results -
 Account No      GL Total
 2101-00-137     2033.60
 4101-00-137     83765.86
 6101-00-137     302656.23

我希望能够将两个结果加在一起进行比较,但我相信它会重复GL总计中每一行的总和,然后再将它相加,它会出现大数字,如 -

 select A.ACTNUMST as [Account No], sum(B.EXTDCOST) as [IV Total], SUM(C.PERDBLNC) as [GL Total]
 from GL00105 A
 INNER JOIN SEE30303 B on A.ACTINDX = B.IVIVINDX
 LEFT JOIN GL10110 C on A.ACTINDX = C.ACTINDX
 group by A.ACTNUMST

 Results -
 Account No      IV Total        GL Total
 2101-00-137     2033.60         14235.20
 4101-00-137     83765.86        116350696.20
 6101-00-137     301984.23       1612897825.84

什么时候应该

 Results -
 Account No      IV Total        GL Total
 2101-00-137     2033.60         2033.60
 4101-00-137     83765.86        83765.86
 6101-00-137     301984.23       302656.23

请告知如何使用sum函数来获得正确的结果。

2 个答案:

答案 0 :(得分:0)

你想要这样的东西吗?如果这不符合预期,请检查并评论。

另请纠正任何语法错误。

SELECT T1.[Account No], T1.[IV Total], T2.[GL Total] FROM
(
    select A.ACTNUMST as [Account No], sum(B.EXTDCOST) as [IV Total]
    from GL00105 A
    INNER JOIN SEE30303 B on A.ACTINDX = B.IVIVINDX
    group by A.ACTNUMST
) T1
INNER JOIN
(
    select A.ACTNUMST as [Account No], SUM(C.PERDBLNC) as [GL Total]
    from GL00105 A
    LEFT JOIN GL10110 C on A.ACTINDX = C.ACTINDX
    group by A.ACTNUMST
) T2
ON T1.[Account No] = T2.[Account No]

希望这有帮助

答案 1 :(得分:0)

这可以通过多个cte来完成

 with IVTotal as
 (
     select A.ACTNUMST, sum(B.EXTDCOST) as [IV Total]
     from   GL00105 A
     INNER  JOIN SEE30303 B 
     on     A.ACTINDX = B.IVIVINDX
     group  by A.ACTNUMST
 ),  
 GLTotal as 
 (
     select A.ACTNUMST as [Account No], SUM(C.PERDBLNC) as [GL Total]
     from   GL00105 A
     LEFT   JOIN GL10110 C 
     on     A.ACTINDX = C.ACTINDX
     group  by A.ACTNUMST
 )
 select a.*,b.[GL Total] 
 from   IVTotal a ,GLTotal b
 where  a.ACTNUMST =  b.aCTNUMST