【发布时间】:2016-05-03 05:50:02
【问题描述】:
自昨天以来,我正在尝试以下查询,其中包含 33 条员工记录,其中员工 ID 处于各种条件下:
With CTE
(
select EmployeeId, and other colums with joins and conditions.
)
现在我想加入这个查询,从下表 table1 和 table2 中获取每个员工的发票总和。
table1 有 employeeid 所以我的 CTE 有 employeeid 我可以加入 table1
With CTE
(
select EmployeeId, and other colums with joins and conditions.
)
select *, table1.invoiceId
from CTE
left join table1 on table1.employeeid = CTE.employeeId
left join table2 on table2.invoiceid = table1.invoiceid
groupby
但我的表 1 只有发票,并且对于每张此类发票,其他表(即表 2)中都有支出金额。 table2 有我需要根据 invoiceid 汇总的“金额”列。
为了更清楚,我正在编写如下表结构或输出。 我正在尝试像上面那样,但他们没有显示正确的结果
假设 CTE 有
Emplyeeid empName Empaddress empcode
1 john America 121
2 sandy America 122
现在 table1 有
InvoiceId EmployeeId RecordId PAyeeid
1 1 223 202
2 1 222 212
3 1 121 378
4 2 229 987
5 2 345 333
table2 有我们每张 epmloyee 发票所需的库尔姆金额
现在表2
InvLine Invoiceid Amount
1 1 30
2 1 30
3 1 20
4 2 10
5 2 10
6 2 10
输出应根据员工 john 在表 1 中有两张发票,即 ID 为 1 和 2,对于 1 和 2 发票,有需要加起来的金额
Emplyeeid empName Empaddress empcode Amount
1 john America 121 80
【问题讨论】:
标签: sql-server sql-server-2008 sql-server-2005 sql-server-2012 sql-server-2012-express