sql query -join获取以下结果

时间:2012-03-24 07:03:26

标签: asp.net sql

我有2个表,从这2个表结果中,我需要得到第3个表,我的第1个表查询结果如下

select categeoryid,EmployeeId,SUM(Amount)as advance
from ExpenditureDetails where Expenditurefor='Travel' and EmployeeId='TFIPL201145' 
group by categeoryid,EmployeeId 

categeoryid            EmployeeId           advance
----------------------------------------------------
Local_IPL              TFIPL201145          1000
Project_Audio release  TFIPL201145          566565
Project_Cricketscore   TFIPL201145          441898
Project_mayajal        TFIPL201145          1100
Project_Tennis         TFIPL201145          8949

第二表结果如下

select categeoryid,EmployeeId,SUM(Amount)as submitted_amt
from ExpenditureTravelling where EmployeeId='TFIPL201145'  
group by categeoryid,EmployeeId

categeoryid          EmployeeId     submitted_amt
-------------------------------------------------
Event_Golf           TFIPL201145    36456
Events_Hokey         TFIPL201145    1303
local                TFIPL201145    25000
Local_IPL            TFIPL201145    1169488
Project              TFIPL201145    16000
Project_Cricketscore TFIPL201145    216661
Project_harris       TFIPL201145    53453
Project_mayajal      TFIPL201145    1500
Project_Tennis       TFIPL201145    8949

我希望我的结果表应该是......加入2表

categeoryid               EmployeeId        advance      submitted_amt
----------------------------------------------------------------------
Event_Golf                TFIPL201145       0            36456
Events_Hokey              TFIPL201145       0            1303
local                     TFIPL201145       0            25000
Local_IPL                 TFIPL201145       1000         1169488
Project                   TFIPL201145       0            16000
Project_Cricketscore      TFIPL201145       441898       216661
Project_harris            TFIPL201145       0            53453
Project_mayajal           TFIPL201145       1100         1500
Project_Tennis            TFIPL201145       8949         8949

可以为这个查询提供帮助......获得结果......

2 个答案:

答案 0 :(得分:0)

您必须使用它们之间的相对链接加入两个查询。据我所知,EmployeeId是一个很好的候选人。类似的东西:

select categoryId, EmployeeId, SUM(Amount) as advance, Travelling.submitted_amt
from ExpenditureDetails inner join
 (select CategoryId, EmployeeId, sum(Amount) as submitted_amt
  from ExpenditureTravelling) as Travelling on
 ExpenditureDetails.EmployeeId = Travelling.EmployeeId
where
  (EmployeeId='TFIPL201145') group by....

希望这有帮助。

答案 1 :(得分:0)

选择a.categoryId,a.EmployeeId,isnull(sum(a.Amount),0)as submitted_amt, isnull((选择sum(b.amount)来自ExpenditureDetails b,其中b.categoryId = a.categoryId和b.Expenditurefor ='Travel'group by b.categeoryid,b.EmployeeId)),0)as advance 来自支出详情a 其中a.EmployeeId ='TFIPL201145'
a.categeoryid分组,a.EmployeeId