表1
Acct Numb Account Type Asset Mkt Val Acct Asset MV
--------- ------------ ------------- -------------
881009201 Main Account 30 120
881009201 Main Account 40 120
881009201 Main Account 20 120
881009201 Main Account 30 120
881009203 Sub Account 50 80
881009203 Sub Account 10 80
881009203 Sub Account 20 80
表2
Acct Numb Account Type Asset Mkt Val Acct Asset MV
--------- ------------ ------------- -------------
881009201 Main Account 30 200
881009201 Main Account 40 200
881009201 Main Account 20 200
881009201 Main Account 30 200
881009201 Sub Account 80 200
我有Table1以及上面给出的信息。我有两种类型的帐户:
现在,我需要一张表,其中包含所有主要帐户和子帐户合并为一个帐号,其中帐号将与其主帐号相同,但帐户类型将为{ {1}}。
现在我们还有两列:
在表1中:列Sub Account
显示主帐户的总和(30 + 40 + 20 + 30 = 120),Acct Asset MV
显示子帐户的总和(50 + 10 + 20 = 80)。
现在在表2中:我希望Asset Mkt Val
包含所有帐户的总和(120 + 80 = 200),在子帐户中,[Asset Mkt Val]应该是80.
答案 0 :(得分:0)
在我看来,Table2的数据可以推导如下:
首先创建一个名为[Table1Totals] ...
的已保存查询SELECT
Left([Acct Numb],Len([Acct Numb])-2) AS [Acct Root],
Right([Acct Numb],2) AS [Acct Suffix],
First(Table1.[Account Type]) AS [FirstOfAccount Type],
Sum(Table1.[Asset Mkt Val]) AS [SumOfAsset Mkt Val]
FROM Table1
GROUP BY
Left([Acct Numb],Len([Acct Numb])-2),
Right([Acct Numb],2);
...返回...
Acct Root Acct Suffix FirstOfAccount Type SumOfAsset Mkt Val
--------- ----------- ------------------- ------------------
8810092 01 Main Account 120
8810092 03 Sub Account 80
然后Table2的数据将是主帐户记录的UNION(“* 01”)和每个子帐户的单个记录(“* 03”):
SELECT
t1.[Acct Numb],
t1.[Account Type],
t1.[Asset Mkt Val],
(
SELECT SUM(t1t1.[SumOfAsset Mkt Val])
FROM Table1Totals t1t1
WHERE t1t1.[Acct Root]=Left(t1.[Acct Numb],Len(t1.[Acct Numb])-2)
) AS [Acct Asset MV]
FROM Table1 t1
WHERE t1.[Acct Numb] LIKE "*01"
UNION ALL
SELECT
t1t2.[Acct Root] & "01" AS [Acct Numb],
t1t2.[FirstOfAccount Type] AS [Account Type],
t1t2.[SumOfAsset Mkt Val] AS [Asset Mkt Val],
(
SELECT SUM(t1t3.[SumOfAsset Mkt Val])
FROM Table1Totals t1t3
WHERE t1t3.[Acct Root]=t1t2.[Acct Root]
) AS [Acct Asset MV]
FROM Table1Totals t1t2
WHERE t1t2.[Acct Suffix] = "03"
...返回...
Acct Numb Account Type Asset Mkt Val Acct Asset MV
--------- ------------ ------------- -------------
881009201 Main Account 30 200
881009201 Main Account 40 200
881009201 Main Account 20 200
881009201 Main Account 30 200
881009201 Sub Account 80 200