2013-12-23 95 views
-2

我有SQL Server 2008中的2個表,我想從這兩個表使用連接的細節。如何從SQL Server中的兩個表中獲取值?

T-1:vwHardwareConsolidate

|ID|||Qty|Type|Task_Id| 

T-2:

|MasterID|Task_Id|Act_Qty| 

我想從T2

T1Masterid, Act_Qty得到id, task_name, sum(qty), task_id我已經試過此查詢

select 
    ID as MasterID, Task_id, Task_Name as Items, 
    SUM(Qty) as Req_Qty, 0 as Act_Qty 
from 
    vwHardwareConsolidate 
where 
    type = 'Reqrd' and ID = '21' 
Group by 
    Task_Name,id,Task_id 

union 

(select 
    m.MasterID, m.Task_Id, vw.Task_Name as Items, 0 as Req_Qty, m.Act_Qty 
from 
    vwHardwareConsolidate vw 
Right join 
    (select 
      MasterID, m.Task_Id, 0 as Req_Qty, sum(Act_qty) as Act_Qty 
     from 
      tbl_MaterialDistribution_Detail m 
     where 
      MasterID = '21' 
     group by 
      m.Task_Id, MasterID) as m on m.Task_Id = vw.Task_id) 

vwHardwareConsolidate

ID Site_name Qty  Task_Name  Type 

1 CITY 1 A16Port_Switch Reqrd 
1 CITY 1 Digital_Camera Reqrd 
1 CITY 1 Electronic_Pen Reqrd 

tbl_MaterialDistribution_Detail

MasterID|TaskId|Act_qty 
7 31 1 
2 32 1 
12 39 3 
+0

總和(數量)請解釋總和是如何計算的,請提供樣本數據 –

+0

請與產出表提供樣品 –

回答

0

您可以使用

SELECT T1.Id, T1.SiteName,T1.TaskName,T.Type,T2.Act_Qty,T2.MasterID,T2.Task_Id,SUM(Qty)AS 
Qty FROM T1 INNER JOIN T2 ON T1.Task_Id=T2=Task_Id GROUP BY T1.Id, T1.SiteName, 
T1.TaskName,T.Type,T2.Act_Qty,T2.MasterID,T2.Task_Id 
0

請試試這個

select t1.ID, t1.Task_Name,Sum(t1.Qty) as Qty,t1.Task_Id,t2.MasterID,t2.Act_Qty 
from vwHardwareConsolidate as t1 
left outer join table2 as t2 
on t2.Task_ID=t1.Task_ID 
Group By t1.ID, t1.Site_name, t1.Task_Name,t1.Qty,t1.Type,t1.Task_Id,t2.MasterID,t2.Act_Qty 

願這能幫助你。

SQL Fiddle Demo

0

東西這種方式,

select a.id,a.Task_Name,b.qty,c.Act_Qty from vwHardwareConsolidate a inner join 
tbl_MaterialDistribution_Detail c on a.id=c.task_id 
inner join 
(slect id,sum(qty)qty from vwHardwareConsolidate group by id)b 
on a.id=b.id 
相關問題