0

加入:クエリSQL Serverは、CTEを使用して合計を取得すると、私は様々な条件での社員と従業員の一部33を記録して昨日からしようとしていますクエリ下記ている

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

今、私はこれに参加したいが次の表table1およびtable2から各従業員の請求書の合計を取得するクエリ。私の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 

しかし、私のTABLE1と一緒に参加することができる唯一の請求書を持っているこのような各請求書の金額があるよう

table1はそうemployeeidを持っている他のテーブルすなわちテーブル2で過ごします。 table2には、請求額に応じて合計する必要がある列「金額」があります。

もっと分かりやすくするために、以下のようなテーブル構造や出力を書いています。 私は上記のようにしようとしていますが、彼らは正しい結果

を示すされていません

は、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の各請求書に必要coulmm量を持っています

nowテーブル2

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

employeあたりのジョンは、ID 1と2でTABLE1、すなわち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が単純なものであれば、2番目のcteに行く必要はありません。

関連する問題