0

我有我從昨天起與僱員在各種條件下試圖與員工的一些33記錄如下查詢:查詢SQL Server中使用CTE獲得總和,並加入

With CTE 
(
    select EmployeeId, and other colums with joins and conditions. 
) 

現在我想加盟此查詢以從下表table1和table2中獲得每個員工的發票總和。

table1employeeid使我的CTE有employeeid我可以用表1

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 

加入它,但我table1的只有發票和爲每個這樣的發票有量在其他表即表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 

表2具有我們需要的epmloyee的每張發票的coulmm量

現在的表2

InvLine  Invoiceid Amount 
1    1   30 
2    1   30 
3    1   20 
4    2   10 
5    2   10 
6    2   10 

輸出應該按僱工約翰在表1,即兩份發票ID爲1和2,1個2 invoiceds有需要被合計達

Emplyeeid empName Empaddress empcode Amount 
1   john America 121  80 

回答

3
With CTE 
    (
    select EmployeeId, and other colums with joins and conditions. 
    ) 

    With CTE1 
    (
    select EmployeeId,table1.invoiceid 
    from cte 
    left join table1 on table1.employeeid=CTE.employeeId 
    ) 

    select sum(amount), cte1.employeeId from CTE1 
    left join table2 on table2.invoiceid = cte1.invoiceid 
    group by cte1.employeeId 

但你可以在第一個cte本身加入table1。如果第一個cte是簡單的,那麼沒有必要去第二個cte。