我有两个临时表来计算一些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
删除sum()
,除非你想聚合。此外,由于表中每个只包含一行,因此可以通过使用交叉连接来简化这一点。
SELECT n.[Note Count],
o.[Order Count],
n.[Note Count] + o.[Order Count] [Total]
FROM #note n
CROSS JOIN #order o;
虽然从临时表中选择单个列没有语法错误,但显而易见的是,您使用整个临时表来保存单个值,即总和。整数变量也可以保持计数。例如:
DECLARE @order int =
(
select count (a.patientSID)
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'
)
DECLARE @note int = (
select count (a.patientSID)
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 @note AS [note count]
,@order AS [order count]
,@order + @note AS [total]