简体   繁体   中英

how to adjust the sum() of a group using the sum() of a subgroup()

I am trying to get the Output shown in the third table below using the tables "Assets" and "Transactions".

I am trying to group by Cmpy, Acct and AssetID and get the Sum(cost). But each cost has to be adjusted from the Transactions table before being summed. Not sure how to do it.

Table: Assets

+----------+------+---------+--------+
|     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 |
+----------+------+---------+--------+

Table: Transactions

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

OUTPUT

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

This one should give you an accurate answer:

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 .

Essentially, SUM the adjustment amounts in the transactions table, then join this to the main results list, summing the cost plus the adjustment for each asset in each account.

If the " relationship " between Acct and AssetID values are 1 to many then you could use this query (which is not so efficient):

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM