添加列,该列返回给定特定主题的最新条目的日期

时间:2014-11-11 19:27:25

标签: sql-server-2008-r2

我对SQL很新,我认为这是一个快速修复:下面是我们办公室中使用的软件的当前Raw SQL。我想在“pronotes”表中添加一个返回最新条目日期的列,其中pronotes.subject =“Patient Contact”。该列标题为“Last Pt.Contact”。我不知道这是否是足够的信息,或者这是一个快速解决方案还是一个大问题。提前感谢你。

编辑这是表格结构。 OT的主键看起来是Orderno

小时


MRN

PTNAME

PTADDRESS

*所有其他领域**


PRONOTES


MRN

SUBJECT

DATE _

BODY

*所有其他领域


OT


ORDERS NO

MRN

*所有其他领域

SELECT 
CASE WHEN OT.STAT=1 THEN 'STAT' ELSE '    ' END AS 'STAT', 
HR.LAST_NAME AS 'LAST_NAME', 
HR.FIRST_NAME AS 'FIRST_NAME',
HR.REFERRAL AS 'REFERRAL_SOURCE',
HR.PHONE AS 'PHONE', 
OT.ORDERED AS 'ORDERED', 
OT.DESCRIP AS 'DESCRIP', 
PTSHIP.SH_ADDR AS 'SH_ADDR', 
CASE WHEN OT.INSNO=99999 THEN 'PATIENT' ELSE INSCOMP.ORG END AS 'ORG', 
OT.INUSE AS 'INUSE', 
OT.TICKINFONO AS 'TICKINFONO', 
OT.NO AS 'NO', 
OT.MRN AS 'MRN', 
LABELS.SCRIPTEXT AS 'SCRIPTEXT',
labels.cpk_labels,
HR.SSN,
OT.ENTSTATUSCHANGED,    
P_ENTSTATUS.INITIALS AS ENTSTATUSBY, 
POP_ENTSTATUS.TEXT_ AS ENTSTATUS,
dbo.f_GetLastEligCheckDate(hr.cpk_hr,ot.insno) as lastcheck,
dbo.f_GetPrimaryPhone(hr.cpk_hr) as PrimaryPhone,
POP_LASTEVENT.TEXT_ AS LASTEVENT
FROM OT
INNER JOIN HR ON HR.DELFLAG = 0 AND HR.MRN = OT.MRN
LEFT JOIN LABELS ON LABELS.DELFLAG = 0 AND LABELS.ORDERNO = OT.NO
LEFT JOIN INSCOMP ON INSCOMP.DELFLAG = 0 AND INSCOMP.NO = OT.INSNO
LEFT JOIN PTSHIP ON PTSHIP.DELFLAG = 0 AND PTSHIP.MRN = OT.MRN
LEFT JOIN POPUPDATA POP_ENTSTATUS ON POP_ENTSTATUS.DELFLAG = 0 AND POP_ENTSTATUS.CPK_POPUPDATA = OT.CFK_POPUPDATA_ENTSTATUS
LEFT JOIN PNNAMES P_ENTSTATUS ON P_ENTSTATUS.DELFLAG = 0 AND P_ENTSTATUS.NO = OT.CFK_PNNAMES_ENTSTATUS
LEFT JOIN POPUPDATA POP_LASTEVENT ON POP_LASTEVENT.DELFLAG = 0 AND POP_LASTEVENT.CPK_POPUPDATA = OT.CFK_POPUPDATA_ENTSTATUS_LASTEVENT
WHERE OT.DELFLAG = 0 AND
OT.LISTID = 'H-NEWORDER' AND
OT.DRUG = 0 AND
OT.THERAPY = 1

1 个答案:

答案 0 :(得分:0)

您需要找到患者的最新日期。我建议你在你在主查询中加入的子查询中这样做。

SELECT
  ...
  LastPatientContact.Date as 'Last Pt. Contact'
FROM OT
  ...
LEFT JOIN (
  SELECT MRN, MAX(date) as Date
  FROM pronotes
  WHERE subject = 'Patient Contact'
  GROUP BY MRN
) LastPatientContact
  ON LastPatientContact.MRN = OT.MRN