[英]How to combine the results of two different queries into a single query in SQL
[英]how to combine two results in single query in 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
在此查询中我输入了月份,因此它将显示该月份的记录
noofinc amtsum cl_id Grandtotal 5 7.00 100000_Pri 7.00 12 2510.12 100001_pro 2510.12
但在此查询结果中如果我输入月份也显示错误,则也应显示(请参阅amtsum列的第一查询结果)Grandtotal为
245 181110.29
使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.