2014-03-27 53 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