将SQL查询的各列连接在一起

时间:2018-08-01 16:49:55

标签: sql sql-server tsql

我有以下两个查询,我想弄清楚是否可以合并到一个查询中。两个表的三列完全相同,但是在许多情况下两者的组织名称将不同。查询就像这样:

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

有可能吗?

2 个答案:

答案 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;