我需要創建患者人口普查報告,顯示給定時間段內每小時和每週每天的平均患者人數。例如,這可以讓我顯示,在過去的6個月中,星期一的急診室平均有4人。我有一個表值函數,將顯示以下患者: VisitID,FromDateTime,ThruDateTime,LocationID。SQL Server患者普查平均按天和小時
我能夠使用下面的代碼顯示例如ER中給定日期的患者人數。但它僅限於一天。 (改編自http://www.sqlservercentral.com/Forums/Topic939818-338-1.aspx)。
--Census Count by Date Range--
DECLARE @BeginDateParameter DateTime, @EndDateParameter DateTime
SET @BeginDateParameter = '20160201'
SET @EndDateParameter = '2016-02-01 23:59:59.000'
----------------------------------------------------
-- Create a temp table to hold the necessary values
-- plus an extra "x" field to track processing
----------------------------------------------------
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
CREATE TABLE #Temp (ID INT Identity NOT NULL, VisitID VarChar(100), SourceID VarChar(100),
FromDateTime DateTime, ThruDateTime DateTime, x INT)
----------------------------------------------------
-- Populate the temp table with values from the
-- the actual table in the database
----------------------------------------------------
INSERT INTO #Temp
SELECT VisitID, FromDateTime, ThruDateTime
FROM PatientFlowTable(BeginDateParameter,@EndDateParameter)
WHERE (FromDateTime BETWEEN @BeginDateParameter AND @EndDateParameter +1
OR ThruDateTime BETWEEN @BeginDateParameter AND @EndDateParameter +1)
AND LocationID = 'ER'
-- Given Period is taken as inclusive of given hours in the input (eg. 15:25:30 will be taken as 15:00:00)
-- frist make sure that the minutes, seconds and milliseconds are removed from input range for clarity
set @BeginDateParameter = dateadd(hh, datepart(hh,@BeginDateParameter), convert(varchar(12),@BeginDateParameter,112))
set @EndDateParameter = dateadd(hh, datepart(hh,@EndDateParameter), convert(varchar(12),@EndDateParameter,112))
-- you may create this CTE by other ways (eg. from permanent Tally table)...
;with dh
as
(
select top 24
DATEADD(hour,ROW_NUMBER() OVER (ORDER BY [Object_id])-1,convert(varchar(12),@BeginDateParameter,112)) as HoDstart
,DATEADD(hour,ROW_NUMBER() OVER (ORDER BY [Object_id]),convert(varchar(12),@BeginDateParameter,112)) as HoDend
,ROW_NUMBER() OVER (ORDER BY Object_id)-1 as DayHour
from sys.columns -- or any other (not very big) table which have more than 24 raws, just remamber to change
-- [Object_id] in OVER (ORDER BY [Object_id]... to some existing column
)
select d.DayHour, count(w.VisitID) as PatientCount
from dh d
left join #Temp w
on w.[FromDateTime] < d.HoDend
and w.[ThruDateTime] >= d.HoDstart
where d.HoDstart between @BeginDateParameter and @EndDateParameter
group by d.DayHour
order by d.DayHour
SELECT VisitID, FromDateTime, ThruDateTime
FROM PatientFlowTable(BeginDateParameter,@EndDateParameter)
WHERE (FromDateTime BETWEEN @BeginDateParameter AND @EndDateParameter +1
OR ThruDateTime BETWEEN @BeginDateParameter AND @EndDateParameter +1)
AND LocationID = 'ER'
前3個小時的輸出示例顯示出現在ER中的患者考慮到他們的出發時間。
Hour PatientCount
0 2
1 3
2 3
這是不是很清楚你在問什麼。 – mendosi