如何在sql中在单个查询中组合两个结果
我有这个疑问如何在sql中在单个查询中组合两个结果,sql,sql-server,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 J
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
在这个查询中,我输入了月份,因此它会显示该月份的记录
noofinc amtsum cl_id Grandtotal
5 7.00 100000_Pri 7.00
12 2510.12 100001_pro 2510.12
noofinc amtsum cl_id Grandtotal
5 7.00 100000_Pri 7.00
12 2510.12 100001_pro 2510.12
但在此查询结果中,如果我输入了月份,则显示错误,也应显示该结果(请参见AMSUM列的第一个查询结果)
格兰道尔是
245
181110.29
245
181110.29
确定记录是否在所需月份的用例。选择所有记录(no where子句),并使用该大小写表达式决定是添加值还是忽略值。在下面的示例中,我构建了一个flag month_匹配以增强可读性。为此,我必须首先构建一个子查询。没有必要;我只是更喜欢这样
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;
第二个查询无法显示提到的结果,因为它的选择列表中有3列,而不是结果中提到的4列。在上一个查询结果amtsum列中,我需要将它添加到第二个查询中,您使用的是哪个
RDBMS
?请不要反复发布相同的问题。它的给出错误“关键字“group”附近的语法不正确。”
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;