两个临时表的SQL加法

时间:2018-08-30 00:52:30

标签: sql sql-server addition

我有两个临时表,它们正在计算许多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

2 个答案:

答案 0 :(得分:2)

删除sum(),除非您要汇总。另外,由于每个表仅包含一行,因此可以通过使用交叉联接将其简化一点。

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

答案 1 :(得分:0)

虽然从临时表中选择单个列在语法上没有错,但很明显,您正在使用整个临时表来保存单个值(合计和)。整数变量也可以保存计数。例如:

{{1}}