如何在sql中单个查询中组合两个结果

时间:2014-03-27 07:45:22

标签: sql sql-server

我有这个查询

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

在此查询中已输入月份,因此它将显示月份记录

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

但是在这个查询结果显示错误,如果我输入月份也应该显示(参见amtsum列的第一个查询结果) Grandtotal是

 245
 181110.29

1 个答案:

答案 0 :(得分:0)

使用CASE确定记录是否在所需的月份内。选择所有记录(无where子句)并使用该case表达式来决定是添加值还是忽略它。在下面的例子中,我构建了一个标志month_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;