2014-03-26 123 views
0

我有這個疑問SQL三個表連接查詢

select 
    dbo.CLOI_ClientOrderItems.cl_id, 
    count(dbo.IN_Invoices.MasterOrderId) as Orders, 
    sum(dbo.IN_Invoices.in_total) as Total 
from 
    IN_Invoices 
inner join 
    CLOI_ClientOrderItems 
on 
    IN_Invoices.MasterOrderId=CLOI_ClientOrderItems.MasterOrderId 
where 
    datepart(mm,in_date_issued)=2 
and 
    datepart(yyyy,in_date_issued)=2014 
group by 
    cl_id 

select 
    sum(in_total) 
from 
    IN_Invoices 
where 
    datepart(mm,in_date_issued)=2 
and 
    datepart(yyyy,in_date_issued)=2014 

從這個查詢我得到的in_total結果,並使用此查詢我需要顯示cl_id和計數(順序)

+0

你能描述你想要的輸出嗎? – jpw

+0

你的第一個查詢doosen't工作? –

+0

cl_id訂單總數 100000_ori 4 476 bur其錯誤 – user3445262

回答

0

假設您正在查找每個cl_id的總體總數,您可以將其添加到SELECT中。否則,您需要將cl_id添加到第二個查詢中,並像第一個示例中那樣執行INNER JOIN。

DECLARE @param1 integer = 2 
DECLARE @param2 integer = 2014 

select 
dbo.CLOI_ClientOrderItems.cl_id, 
count(dbo.IN_Invoices.MasterOrderId) as Orders, 
sum(dbo.IN_Invoices.in_total) as Total, 
OverallTotal = (select sum(in_total) from IN_Invoices where datepart(mm,in_date_issued)[email protected] and datepart(yyyy,in_date_issued)[email protected]) 
from 
IN_Invoices 
inner join 
CLOI_ClientOrderItems 
on 
IN_Invoices.MasterOrderId=CLOI_ClientOrderItems.MasterOrderId 
where 
datepart(mm,in_date_issued)[email protected] 
and 
datepart(yyyy,in_date_issued)[email protected] 
group by 
cl_id 
+0

其中cond使用兩次... – user3445262

+0

請參閱編輯。這通常意味着您需要將其作爲存儲過程進行包裝。 – smoore4

+0

我有3張桌子我怎麼發送你 – user3445262