Mssql< 2005
我有一个包含大量表的复杂数据库,但现在只有患者表和测量表很重要。
我需要的是'code'
的最新值与某个值匹配的患者数。此外,日期测量必须在'2012-04-01'之后。我已经用两种不同的方式解决了这个问题:
SELECT
COUNT(P.patid)
FROM T_Patients P
WHERE P.patid IN (SELECT patid
FROM T_Measurements M WHERE (M.code ='xxxx' AND result= 'xx')
AND datemeasurement =
(SELECT MAX(datemeasurement) FROM T_Measurements
WHERE datemeasurement > '2012-01-04' AND patid = M.patid
GROUP BY patid
GROUP by patid)
和
SELECT
COUNT(P.patid)
FROM T_Patient P
WHERE 1 = (SELECT TOP 1 case when result = 'xx' then 1 else 0 end
FROM T_Measurements M
WHERE (M.code ='xxxx') AND datemeasurement > '2012-01-04' AND patid = P.patid
ORDER by datemeasurement DESC
)
这很好用,但它使得查询非常慢,因为它必须加入子查询上的外表(如果你知道我的意思)。查询在没有最近检查的情况下需要10秒,在最近一次检查时需要3分钟。
我很确定这可以更高效地完成,所以如果你愿意,请赐教我。)。
我尝试实施HAVING datemeasurment=MAX(datemeasurement)
,但不断向我投掷错误。
答案 0 :(得分:1)
因此,我的方法是编写一个查询,以获取自2012年4月1日以来的所有最后一次患者结果,然后对您的代码和结果进行过滤。像
这样的东西select
count(1)
from
T_Measurements M
inner join (
SELECT PATID, MAX(datemeasurement) as lastMeasuredDate from
T_Measurements M
where datemeasurement > '01-04-2012'
group by patID
) lastMeasurements
on lastMeasurements.lastmeasuredDate = M.datemeasurement
and lastMeasurements.PatID = M.PatID
where
M.Code = 'Xxxx' and M.result = 'XX'
答案 1 :(得分:1)
最快的方法可能是使用row_number()
:
SELECT COUNT(m.patid)
from (select m.*,
ROW_NUMBER() over (partition by patid order by datemeasurement desc) as seqnum
FROM T_Measurements m
where datemeasurement > '2012-01-04'
) m
where seqnum = 1 and code = 'XXX' and result = 'xx'
Row_number()
枚举每位患者的记录,因此最近得到的值为1.结果只是一个选择。