如果可以的话,另一个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');
答案 0 :(得分:0)
使用2个表deb
和cred
的连接的一种方法如下:
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
字段)一致。
另一种方法是UNION
,GROUP 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}}