【发布时间】:2018-10-04 18:59:35
【问题描述】:
我有一个费用报告应用程序,可将费用费用和帐号收集到一个表格中,但可以将给定费用拆分为一部分记入一个 GL 帐户,其余部分记入另一个帐户。为了适应成本拆分,费用表有两对金额和帐号列,供数据输入过程使用。像这样:
create table Expenses (expheaderid int, explineid int, amount_split1 decimal(5,2),
account int, amount_split2 decimal(5,2), account2 int);
insert Expenses values (57, 11, 47.35, 80400, 0, 0);
insert Expenses values (57, 12, 163.31, 80440, 0, 0);
insert Expenses values (57, 13, 30, 80401, 5.90, 70410);
insert Expenses values (57, 14, 35, 80440, 0, 0);
insert Expenses values (57, 15, 45.15, 80440, 0, 0);
insert Expenses values (57, 16, 145.87, 80400, 68.14, 80400);
insert Expenses values (57, 17, 67.35, 80870, 0, 0);
insert Expenses values (57, 18, 105, 80402, 34.50, 80440);
我需要汇总 (GROUP BY) 来自相同帐户代码的金额,但汇总必须发生在两对金额和帐号列之间 - (amount_split1 & account) 第一对或 (amount_split2 & account 2)第二列对。所以我的表是这样的:
expheaderid explineid amount_split1 account amount_split2 account2
----------- --------- ------------- ------- ------------- --------
57 11 47.35 80400 0.00 0
57 12 163.31 80440 0.00 0
57 13 30.00 80401 5.90 70410
57 14 35.00 80440 0.00 0
57 15 45.15 80440 0.00 0
57 16 145.87 80400 68.14 80400
57 17 67.35 80870 0 0
57 18 105.00 80402 34.50 80440
我想将 amount_split1 成本与按帐号分组的 amount_split2 成本合并。
结果应如下所示,从 account 列和 account2 列中的 GL 帐户中收集
AggTotal GLAccount
-------- ---------
261.36 80400
30.00 80401
105.00 80402
277.96 80440
67.35 80470
and probably...
0.00 0 -which I don't care about.
我根本不擅长复合查询。我正在尝试通过这样的一个语句来 UNION 和 GROUP:
select sum(AggTotal), GLAccount from
((select amount_split1 as AggTotal, account as GLAccount from Expenses)
union all
(select amount_split2 as AggTotal, account2 as GLAccount from Expenses))as t
where Expenses.expheaderid=57 group by GLAccount;
但是expheaderid 列不会绑定。该数据是更大数据集的一部分,因此 expheaderid 上的 WHERE 子句必须起作用。
感谢您的帮助。
【问题讨论】:
-
至于为什么它不会绑定:你的 from 子句由 1 个表
t组成,所以当 where 子句执行时,它不知道Expenses表。另外表t没有expheaderid列;所以即使我们做了t.expheaderid它也不会被发现。那么您希望 SQL 引擎在哪里找到Expenses.expheaderid?要么将它包含在带有联合的选择中,要么在选择中单独过滤。
标签: sql sql-server group-by union-all