2017-12-28 93 views
0

이 기간 동안 각 환자 ID와 관련된 가장 빠른 날짜를 얻으려고합니다.SQL : 환자 값과 관련된 최소 날짜를 얻는 방법

현재 SQL은 환자 기간 동안 여러 번의 방문/문서를 반환합니다. 날짜 범위의 특정 제공 업체에 연결된 환자에게 가장 빠른 날짜 만 표시해야합니다. PatientID

에 대한

여러 날짜

enter image description here

USE EHR 
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 
    DECLARE @PROV NVARCHAR (255) ='KCOOPER0' 
    DECLARE @START_DATE DATETIME = '2017-09-18 00:00:00.000'  
    DECLARE @END_DATE DATETIME = '2017-12-17 23:59:59.999'  
    --DECLARE @START_DATE DATETIME = '2017-10-02 00:00:00.000'  
    --DECLARE @END_DATE DATETIME = '2017-12-31 23:59:59.999'  

    SELECT DISTINCT 
       PS.ID AS AppointmentID 
       , CL.Code AS PatientID 
--    , SU.NameFirst AS PROVFNAME 
--    , SU.NameLast AS PROVLNAME 
--    , SU.NameSuffix AS PROVSUFFIX 
       , PS.ProviderId 
       , PS.ScheduledDateTime AS AppointmentDT 
       , PS.Duration 
       , PS.[TYPE] AS TypeDescription 
       , PS.IsActive as [Status] 
       , PS.ExternalId AS VisitID 
    --   , REPLACE(REPLACE(LOC.[Description],'[',''),']','') AS LOCATIONPLACE 
       , CDA.CreatedOn AS CDA 
       FROM PatientSchedule PS 
    INNER JOIN ContactsList CL WITH(NOLOCK) ON PS.PatientID=CL.ReferenceID 
    AND CL.Relation = 0 
     AND PS.ScheduledDateTime BETWEEN @START_DATE AND @END_DATE 
    INNER JOIN SystemUsers SU WITH(NOLOCK) ON PS.InterfaceCode=SU.InterfaceCode AND SU.Status='1' 
     INNER JOIN EMRDocuments ED ON PS.ID=ED.PatientScheduleId 
     AND ED.IsActive=1 
     LEFT JOIN 
       (SELECT DISTINCT ED.ID 
       ,SU.NPI 
       ,ED.PATIENTSCHEDULEID 
       ,EDE.CreatedOn 
       FROM 
       EMRDOCUMENTS ED 
       INNER JOIN SystemUsers SU ON ED.ModifiedByID=SU.ID 
       AND ED.IsActive = 1 
       AND ED.IsSignedOff ='TRUE' 
       INNER JOIN EMRDocumentExport EDE ON ED.ID=EDE.DocumentId 
       AND EDE.LabCompanyName = 'FollowMyHealth_CCDA' 
      ) CDA ON PS.ID=CDA.PatientScheduleId 
    WHERE --CL.Code = @PatientID 
       su.RegisteredProvider =1 
       AND SU.UserID [email protected] 
     ORDER BY CL.Code, CDA.CreatedOn 

답변

4

이것은 일반적인 생각이다. 세부 정보를 입력 할 수 있습니다.

select your fields 
from your tables 

join (select patientId, min(the date field you want) minDate 
from your tables 
where whatever 
group by patientId) minDates 

on minDates.patientId = sometable.patientId 
and the date field you want = minDate 

etc 
0

창 함수와 공통 테이블 식 또는 부속 선택으로 고정하는 결합없는 대안.

select field1, field2, ... , AppointmentDT from 
    (select field1, field2, ..., 
    AppointmentDT, 
    min(AppointmentDT) OVER (PARTITION BY PatientID) minptAppointmentDT 
    from table) mindates 
where AppointmentDT = minptAppointmentDT 
: 부속을 사용하여

with mindates as (
    select field1, field2, ..., 
     AppointmentDT, 
     min(AppointmentDT) OVER (PARTITION BY PatientID) minptAppointmentDT 
    from table 
) 

select field1, field2, ... , AppointmentDT from mindate_table 
where AppointmentDT = minptAppointmentDT 

: CTE를 사용