我有一张医院入院表,并且必须根据成人病房类型的记录类型按病房入院。
记录类型是1或2,其中1是直接入场,2是转移。
这是数据的示例(Ward和WardType从查找表中加入): -
IntRefID RecordType StartDate StartTime Ward WardType
1205378364 1 25/04/2016 17:30:00 BR WARD Adult
1205378965 2 26/04/2016 18:00:00 BL WARD HDU
1205402541 1 21/04/2016 01:15:00 SA UNIT SA
1205402541 2 26/04/2016 14:36:00 BR WARD Adult
1205402772 1 21/04/2016 03:11:00 SA UNIT SA
我需要的输出应该是这样的 -
Ward RecordType-1 RecordType-2 Total Transfers from SA
BR WARD 1 1 2 1
BL WARD 0 1 1 0
当病房之间有转移时,IntRefID保持不变。
我一直试图获得SA'转移的总数。
第3和第4行数据显示患者已被SA单位录取然后转入BR Ward的情况。我需要算一下这个转移。
有不同类型的病房,我只需要计算从SA单位到成年病房的转移。
我查看了其他帖子,您可以在其中计算群组的第N个值,或者在这种情况下为N-1,但我无法在一个查询中找出如何将其与常规小计相结合的方法
答案 0 :(得分:1)
尝试以下查询: -
select distinct Ward,
(select count(RecordType) from test5 B where B.Ward=A.Ward AND B.RecordType=1) AS [RecordType-1],
(select count(RecordType) from test5 B where B.Ward=A.Ward AND B.RecordType=2) AS [RecordType-2],
Count(RecordType) over (partition by Ward) AS Total,
(select count(*) from test5 B where B.Ward=A.Ward AND B.RecordType=A.RecordType AND B.WardType='Adult') AS [Transfers from SA]
from test5 A
此查询将为您提供如下输出: -
Ward RecordType-1 RecordType-2 Total Transfers from SA
BL WARD 0 1 1 0
BR WARD 1 1 2 1
SA UNIT 2 0 2 0
答案 1 :(得分:0)
也许是这样的:
select
Ward,
SUM(Case recordType when 1 then 1 end) RecordType-1
SUM(Case recordType when 2 then 1 end) RecordType-2
COUNT(*) Total,
case when RecordType = 2 then l.c end [Transfers from SA]
from myTable t
outer apply (
select
COUNT(*) c
from myTable l
where
l.RecordType = t.RecordType-1 and
Ward = 'SA UNIT' and
t.startDate+t.StartTime > l.startDate+t.starttime
)l
where
t.Ward in ('BR WARD','BL WARD')
group by
t.ward