如何使用子组的sum()调整组的sum()

时间:2013-08-09 16:00:50

标签: sql tsql

我正在尝试使用“资产”和“交易”表格获得下面第三个表格中显示的输出。

我正在尝试按Cmpy,Acct和AssetID进行分组并获得总和(成本)。但在汇总之前,必须从“交易”表中调整每个成本。不知道怎么做。

表:资产

+----------+------+---------+--------+
|     Cpny | Acct | AssetID |  Cost  |
+----------+------+---------+--------+
|       50 |  120 |     109 | 100.00 |
|       50 |  120 |     109 | 200.00 |
|       50 |  120 |     110 | 300.00 |
|       50 |  120 |     110 | 20.00  |
|       50 |  121 |     107 | 150.00 |
|       50 |  121 |     201 | 200.00 |
+----------+------+---------+--------+

表格:交易

+------+---------+--------+
| Cpny | AssetID |  Amt   |
+------+---------+--------+
|   50 |     109 | -50.00 |
|   50 |     110 | 50.00  |
|   50 |     110 | -20.00 |
|   50 |     201 | -50.00 |
+------+---------+--------+

输出

+------+------+--------+
| Cpny | Acct | Total  |
+------+------+--------+
|   50 |  120 | 600.00 |
|   50 |  121 | 300.00 |
+------+------+--------+

2 个答案:

答案 0 :(得分:3)

这个应该给你一个准确的答案:

SELECT  a.Cpny,
        a.Acct,
        SUM(a.Cost + ISNULL(t.Adjustment, 0)) AS Total
  FROM  Assets a
    LEFT JOIN (SELECT  Cpny,
                       AssetID,
                       SUM(Amt) AS Adjustment
                 FROM  Transactions
                 GROUP BY Cpny, AssetID) t
      ON t.Cpny = a.Cpny AND t.AssetID = a.AssetID
  GROUP BY a.Cpny, a.Acct

Associated SQLFiddle here

基本上,汇总交易表中的调整金额,然后将其加入主结果列表,将成本加上每个帐户中每个资产的调整相加。

答案 1 :(得分:0)

如果AcctAssetID值之间的“关系”为1到多,那么您可以使用此查询(效率不高):

SELECT x.Cpny,x.Acct, SUM( ISNULL(x.Total,0) + ISNULL(y.Total,0) ) AS Total
FROM 
(
    SELECT  a.Cpny,a.Acct,a.AssetID, SUM(a.Cost) AS Total
    FROM    dbo.Assets a 
    GROUP BY a.Cpny,a.Acct,a.AssetID
) x
LEFT JOIN
(
    SELECT  t.Cpny,t.AssetID, SUM(t.Cost) AS Total
    FROM    dbo.Transactions t
    GROUP BY t.Cpny,t.AssetID
) y ON x.Cpny=y.Cpny AND x.AssetID=y.AssetID
GROUP BY x.Cpny,x.Acct;