将SQL查询的列连接在一起

将SQL查询的列连接在一起,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有下面两个查询,我想知道我是否可以合并成一个查询。两个表都有完全相同的三列,但在许多情况下,这两个表的组织名称会有所不同。查询如下: 选择OrganizationHierarchyUnitLevelThreeNm,将*计为完成 从完全c 在w.WorkerKey=c.WorkerKey上加入w 按组织层次分组UnitLevelThreeNM 1号订单; 选择OrganizationHierarchyUnitLevelThreeNm,根据需要计算* 通缉犯 按组织层次分组UnitLevelThr

我有下面两个查询,我想知道我是否可以合并成一个查询。两个表都有完全相同的三列,但在许多情况下,这两个表的组织名称会有所不同。查询如下:

选择OrganizationHierarchyUnitLevelThreeNm,将*计为完成 从完全c 在w.WorkerKey=c.WorkerKey上加入w 按组织层次分组UnitLevelThreeNM 1号订单; 选择OrganizationHierarchyUnitLevelThreeNm,根据需要计算* 通缉犯 按组织层次分组UnitLevelThreeNM 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
这可能吗?

您可以使用union all:


又干净又漂亮!请注意:我认为您应该用前缀指明ColumOrganizationHierarchyUnitLevelThreeNM来自哪个表。也许是c,也许是w,事实上。这个问题好吗?它不应该使用外部连接而不是左连接吗?事实上,它可能缺少Bar或Baz,或者两者都缺少。@Impaler,LEFT JOIN是一个外部连接,如果您愿意,可以将其写为LEFT OUTER JOIN。连接可能是一个完整的外部连接,他最了解底层数据。在他的示例查询中,输出似乎不正确。
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;
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;