将两个表汇总到Jet SQL中的一个表中

时间:2014-01-05 23:52:38

标签: sql ms-access sum jet

如果可以的话,另一个SQL问题。

我有两个表(从TRANSFORM生成 - Jet SQL中的PIVOT查询)

Category  ID     Account     Jan     Feb    ...    Dec
1         1      Cash        10      20            30
1         2      Card        100     200           300
1         3      Savings     200     400           600

Category  ID     Account     Jan     Feb    ...    Dec
1         1      Cash        -5      -10           -20
1         2      Card                -100          -200
1         3      Savings     -100                  -400

两个表中的类别,ID和帐户将始终相同。一个表中不会出现在其他表中不存在的帐户。两个表中都可能有NULL值,但每个表中始终会有匹配的单元格。

我想要的是

Category  ID     Account     Jan     Feb    ...    Dec
1         1      Cash        5       10            10
1         2      Card        100     100           100
1         3      Savings     100     400           200

我玩过UNION和JOIN查询,但无法到达那里。

再次感谢, 安迪

编辑 - 原始查询

TRANSFORM Sum(Items.amount) AS total
SELECT Accounts.accCategory, Accounts.ID, Accounts.comment AS Account
FROM Accounts INNER JOIN Items ON Accounts.ID = Items.accFrom
WHERE (((Year([idate]))=2013) AND ((Items.category)<>3 Or (Items.category) Is Null) AND ((Accounts.accCategory)=6 OR (Accounts.accCategory)=7) AND ((Accounts.curr)=1))
GROUP BY Accounts.accCategory, Accounts.ID, Accounts.comment
PIVOT Format(idate,'mmm') IN ('Jan','Feb','Mar','Apr', 'May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');

TRANSFORM Sum(Items.amount) AS total
SELECT Accounts.accCategory, Accounts.ID, Accounts.comment AS Account
FROM Accounts INNER JOIN Items ON Accounts.ID = Items.accFrom
WHERE (((Year([idate]))=2013) AND ((Items.category)=3) AND ((Items.comment)='Monthly') AND ((Accounts.accCategory)=6) AND ((Accounts.curr)=1))
GROUP BY Accounts.accCategory, Accounts.ID, Accounts.comment
PIVOT Format(idate,'mmm') In ('Jan','Feb','Mar','Apr', 'May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');

1 个答案:

答案 0 :(得分:0)

使用2个表debcred的连接的一种方法如下:

SELECT cred.accCategory, cred.ID, cred.Account, [deb].[Jan]+[cred].[Jan] AS tot_Jan
FROM cred INNER JOIN deb ON (cred.Account = deb.Account) AND (cred.ID = deb.ID) AND (cred.accCategory = deb.accCategory);

此屏幕截图显示了查询的构建方式:

以下是结果(请原谅表格格式):

accCategory ID  Account tot_Jan
1   1   Cash    5
1   2   Card    100
1   3   Savings 100

警告JOIN是一个equi-JOIN,这意味着BOTH表中必须存在相同数量的记录,否则您将发现不存在借记的信用将被删除!因此,请确保两个输入表都与相同的键值(早期PIVOT查询中的3个GROUP BY字段)一致。

另一种方法是UNIONGROUP BY来计算总数。SELECT * FROM cred UNION SELECT * FROM deb。我很快就会粘贴它。

==========编辑============

您可以分阶段进行构建。首先我做了UNION并在设计视图中查看。

返回SQL视图,确保SELECT sub.* FROM查询的括号位于其前面,AS SUB括号前,括号后GROUP BY

然后我修改了查询以包含Sum(Jan)SELECT sub.accCategory, sub.ID, sub.Account, Sum(sub.Jan) AS SumOfJan FROM (SELECT * FROM cred UNION SELECT * FROM deb) AS sub GROUP BY sub.accCategory, sub.ID, sub.Account; 位。最后的SQL在这里,截图如下。

{{1}}