首页 > 解决方案 > 两个临时表的 SQL 加法

问题描述

我有两个临时表正在计算一些 ID。我想组合这些表来计算每个表,然后将它们加在一起。这就是我到目前为止所拥有的。

if object_id('tempdb..#order') is not null drop table #order 
select count (a.patientSID) as 'Order Count'

into #order
from CPRSOrder.CPRSOrder a
join sstaff.SStaff b on b.staffSID = a.EnteredbyStaffSID 
join spatient.spatient c on c.patientSID = a.patientSID
where b.staffName = xxxxxxxx
and a.enteredDateTime >= '20180801' and a.enteredDateTime <= '20180828'

if object_id('tempdb..#note') is not null drop table #note 
select count (a.patientSID) as 'Note Count'

into #note
from tiu.tiudocument a
join sstaff.SStaff b on b.staffSID = a.EnteredbyStaffSID 
--join spatient.spatient c on c.patientSID = a.patientSID
where b.staffName = xxxxxxxx
and a.episodeBeginDateTime >= '20180801' and a.episodeBeginDateTime     <= '20180828'

select (select [Note Count] from #note) as 'Note Count',
(select [Order Count] from #order) as 'Order Count',
sum((select [Order Count] from #order) + (select [Note Count] from #note))  as Total

标签: sqlsql-serveraddition

解决方案


删除sum(), 除非你想聚合。此外,由于每个表只包含一行,因此可以通过使用交叉连接来稍微简化一下。

SELECT n.[Note Count],
       o.[Order Count],
       n.[Note Count] + o.[Order Count] [Total]
       FROM #note n
            CROSS JOIN #order o;

推荐阅读