0

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

我正在尝试按 Cmpy、Acct 和 AssetID 分组并获得 Sum(cost)。但是在求和之前,必须从 Transactions 表中调整每个成本。不知道该怎么做。

表:资产

+---------+------+---------+--------+
| 价格 | 帐户 | 资产ID | 成本 |
+---------+------+---------+--------+
| 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 |
+---------+------+---------+--------+

表:交易

+--------+---------+--------+
| 价格 | 资产ID | 安特 |
+--------+---------+--------+
| 50 | 109 | -50.00 |
| 50 | 110 | 50.00 |
| 50 | 110 | -20.00 |
| 50 | 201 | -50.00 |
+--------+---------+--------+

输出

+--------+------+--------+
| 价格 | 帐户 | 总计 |
+--------+------+--------+
| 50 | 120 | 600.00 |
| 50 | 121 | 300.00 |
+--------+------+--------+
4

2 回答 2

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

在这里关联 SQLFiddle 。

本质上,对交易表中的调整金额求和,然后将其加入主结果列表,将成本加总和每个账户中每种资产的调整。

于 2013-08-09T16:21:16.853 回答
0

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

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;
于 2013-08-09T16:12:28.647 回答