我有2个groupby查询,每个查询计算每个compnay_id的行,两者都按company_id分组。 我需要输出一个将打印列qty1,qty2,company_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
答案 0 :(得分:0)
我不是SQL的专家,但LEFT JOIN会为你工作吗? https://www.w3schools.com/sql/sql_join_left.asp
答案 1 :(得分:0)
一个简单的解决方案是:
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
。
这个小技巧允许混合其他不相关的数据。