我有以下两个查询,我想弄清楚是否可以合并到一个查询中。两个表的三列完全相同,但是在许多情况下两者的组织名称将不同。查询就像这样:
SELECT OrganizationHierarchyUnitLevelThreeNm, COUNT(*) AS Complete
FROM #complete c
JOIN #wanted w ON w.WorkerKey = c.WorkerKey
GROUP BY OrganizationHierarchyUnitLevelThreeNm
ORDER BY 1;
SELECT OrganizationHierarchyUnitLevelThreeNm, COUNT(*) AS Wanted
FROM #wanted
GROUP BY OrganizationHierarchyUnitLevelThreeNm
ORDER BY 1;
所以第一个可能最终会是这样的:
OrganizationHierarchyUnitLevelThreeNm | Complete
------------------------------------------------
Foo | 2
Bar | 17
然后是第二个
OrganizationHierarchyUnitLevelThreeNm | Wanted
------------------------------------------------
Foo | 27
Baz | 132
所以在结果查询中,我想要:
OrganizationHierarchyUnitLevelThreeNm | Wanted | Complete
---------------------------------------------------------
Foo | 27 | 2
Bar | 0 | 17
Baz | 132 | 0
有可能吗?
答案 0 :(得分:0)
您可以使用union all
:
select OrganizationHierarchyUnitLevelThreeNm, sum(Wanted), sum(Complete)
from ( (select OrganizationHierarchyUnitLevelThreeNm, 1 as Wanted , 0 as Complete
from #wanted w
) union all
(select OrganizationHierarchyUnitLevelThreeNm, 0 as Wanted , 1 as Complete
from #complete c
)
) t
group by OrganizationHierarchyUnitLevelThreeNm;
答案 1 :(得分:0)
SELECT OrganizationHierarchyUnitLevelThreeNm,
Count(w.WorkerKey) as wanted,
COUNT(c.WorkerKey) AS Complete
FROM #wanted w
LEFT JOIN #complete c ON w.WorkerKey = c.WorkerKey
GROUP BY OrganizationHierarchyUnitLevelThreeNm
ORDER BY 1;