简体   繁体   English

如何在SQL中的单个查询中合并两个结果

[英]how to combine two results in single query in sql

i have this query 我有这个查询

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

the query result is 查询结果是

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

in this queryi haveenterd the month so itll show that month records 在此查询中我输入了月份,因此它将显示该月份的记录

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

but in this query result showing wrong if i enterd month also it should be show (see the 1st query result of amtsum column) Grandtotal is 但在此查询结果中如果我输入月份也显示错误,则也应显示(请参阅amtsum列的第一查询结果)Grandtotal为

245
 181110.29

Use CASE to determine if a record is in the desired month. 使用CASE确定记录是否在所需月份中。 Select all records (no where clause) and use that case expression to decide wether to add a value or ignore it. 选择所有记录(没有where子句),并使用该case表达式决定是否添加值或忽略它。 In below example I have built a flag month_match to enhance readabilty. 在下面的示例中,我建立了一个标记month_match来增强可读性。 For this I had to build a sub query first. 为此,我必须先构建一个子查询。 It's not necessary; 这不是必需的; I just like it better this way. 我喜欢这样更好。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM