SQL сложение двух временных таблиц - PullRequest
0 голосов
/ 30 августа 2018

У меня есть две временные таблицы, которые считают количество идентификаторов. Я хочу объединить эти таблицы, чтобы подсчитать их, а затем сложить их вместе. Это то, что я имею до сих пор.

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 голосов
/ 30 августа 2018

Хотя нет ничего синтаксически неправильного в выборе одного столбца из временной таблицы, ясно, что вы используете целую временную таблицу для сохранения одного значения, агрегированной суммы. Целочисленная переменная также может содержать счетчик. Например:

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]
0 голосов
/ 30 августа 2018

Удалите sum(), если вы не хотите агрегировать. Кроме того, поскольку таблицы содержат только одну строку, это можно немного упростить с помощью перекрестного соединения.

SELECT n.[Note Count],
       o.[Order Count],
       n.[Note Count] + o.[Order Count] [Total]
       FROM #note n
            CROSS JOIN #order o;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...