2014-03-27 54 views
0

單查詢兩個結果結合起來,我有此查詢如何在SQL

Select 
    Count(IN_Invoices.in_id) NoOfInv, 
    sum(in_total) AMTsum, 
    CLOI_ClientOrderItems.cl_Id  
from 
(
    select 
     distinct MasterOrderId, 
     cl_Id 
    from CLOI_ClientOrderItems 
) as CLOI_ClientOrderItems 
inner Join IN_Invoices 
    on IN_Invoices.MasterOrderId=CLOI_ClientOrderItems.MasterOrderId 
group by CLOI_ClientOrderItems.cl_id 

查詢結果

 
noofinc amtsum  cl_id 
7   245  100000pri 
247  181110.29 100001pro 
Select 
    Count(IN_Invoices.in_id) NoOfInv, 
    AMTsum=sum(in_total) , 
    CLOI_ClientOrderItems.cl_Id  
from 
(
    select 
     distinct MasterOrderId, 
     cl_Id 
    from CLOI_ClientOrderItems 
) as CLOI_ClientOrderItems 
inner Join IN_Invoices 
    on IN_Invoices.MasterOrderId=CLOI_ClientOrderItems.MasterOrderId 
where datepart(mm,in_date_issued)=1 and datepart(yyyy,in_date_issued)=2014 
group by CLOI_ClientOrderItems.cl_id 
在此queryi

haveenterd月份這樣ITLL顯示,月記錄

 
noofinc amtsum cl_id   Grandtotal 
5  7.00  100000_Pri 7.00 
12  2510.12 100001_pro 2510.12 

但在此查詢中顯示如果我照耀處也每月應該顯示(見amtsum列的第一個查詢結果)錯誤的結果 Grandtotal是

 
245 
181110.29 
+0

第二個查詢無法顯示提到的結果,因爲它的選擇列表中有3列,而不是結果中提到的4個列。 –

+0

在前面查詢結果amtsum列我需要添加它在第二個查詢 – user3445262

+0

你使用哪個'RDBMS'? –

回答

0

使用案例,以確定是否記錄是所需的月份。選擇所有記錄(no where子句)並使用該案例表達式來決定是否添加值或忽略它。在下面的例子中,我創建了一個flag_match標誌來增強可讀性。爲此,我必須先建立一個子查詢。這不是必需的;我更喜歡這種方式。

select 
    cl_id, 
    sum(case when month_match = 1 then 1 else 0 end) as count_invoices_in_month, 
    sum(case when month_match = 1 then in_total else 0 end) as sum_invoices_in_month, 
    count(*) as count_invoices_total, 
    sum(in_total) as sum_invoices_total 
from 
(
    select 
    i.in_id, 
    i.in_total, 
    cloi.cl_id, 
    case when datepart(mm, i.in_date_issued) = 1 
     and datepart(yyyy, i.in_date_issued) = 2014 then 
     1 
    else 
     0 
    end as month_match 
    from 
    (
    select distinct masterorderid, cl_id from cloi_clientorderitems 
) as cloi 
    inner join in_invoices i on i.masterorderid=cloi.masterorderid 
) 
group by cl_id; 
+0

其提供錯誤「關鍵字'組附近的語法錯誤'。」 – user3445262