Sql 将所有查询中的列打印到一个查询中

Sql 将所有查询中的列打印到一个查询中,sql,Sql,我有两个groupby查询,每个查询为每个公司id统计行数,都是按公司id分组的。 我需要输出一个将打印列qty1、qty2、公司id的查询 工会不适合我: select count(*) as qty1 from T_MISSION where datepart(month, [mdatetime])=12 group by company_id union all select count(*) as qty2 from T_CUSTSK where datepart(month, [

我有两个groupby查询,每个查询为每个公司id统计行数,都是按公司id分组的。 我需要输出一个将打印列qty1、qty2、公司id的查询 工会不适合我:

select count(*) as qty1
from T_MISSION
where datepart(month, [mdatetime])=12
group by  company_id

union all

select count(*) as qty2
from T_CUSTSK
where datepart(month, [sdate])=12
group by  company_id

我不是SQL方面的专家,但我愿意为你工作吗?
一个简单的解决方案是:

select sum(qty1), sum(qty2), company_id
from
(
 select count(*) as qty1, 0 as qty2, company_id
 from T_MISSION
 where datepart(month, [mdatetime])=12
 group by  company_id

 union all

 select 0 as qty1, count(*) as qty2, company_id
 from T_CUSTSK
 where datepart(month, [sdate])=12
 group by  company_id
) as combined
group by company_id
其思想是:为每个值使用单独的列。每个数据收集都将所有其他列设置为
0
,这样它们就不会奇怪地混淆。最后(每个客户)将它们加起来,这样每个列和客户正好有一个值,其他所有值定义为
0


这个小技巧允许混合其他不相关的数据。

否,因为使用group by的每个查询中有2个计数,我假设需要在所有最终表上按进行分组,因为两个查询都按同一个公司分组\u id为什么使用sum()函数?请参阅答案中的说明。Sum()实际上只是一个组合行的技巧。