返回最近的时间

时间:2011-04-11 15:36:18

标签: sql

我有一个复杂的加入程序,我需要在X患者的X日期返回最近的时间。

SELECT  CONVERT(varchar(36), apt.UniqueID), 
        apt.atime, 
        RTRIM(apt.apwork) + ' ' + RTRIM(apt.apwrk2),
        aps.apsdispchar,
        RTRIM(LTRIM(aps.apstextcolor)),
        RTRIM(LTRIM(aps.apsbgcolor)),
        apT.apid,
        dbo.MakeCaseString(pat.pfname, pat.pfnamcase) + ' ' + dbo.MakeCaseString(pat.plname, pat.plnamcase),
        apn.apnentrytime
        FROM apt INNER JOIN pat ON pat.pid = apt.apid INNER JOIN aps on ((apt.aconfstat IS NOT NULL AND apt.aconfstat = aps.apsid) OR (apt.aconfstat IS NULL AND aps.apsid = ' ')) INNER JOIN apn ON (apn.apnpid = apt.apid AND apn.apndate = apt.adate AND apn.apntime = apt.atime)
WHERE apt.adid = @ProviderIDParam   AND apt.adate = @DateParam AND apn.apnentrytime IN (SELECT MAX(apn.apnentrytime) FROM apn)
ORDER BY apt.atime ASC

目前我正在使用:

apn.apnentrytime IN (SELECT MAX(apn.apnentrytime) FROM apn)

它适用于某些数据,而其他数据(相当大),它不会工作。

1 个答案:

答案 0 :(得分:2)

您需要将子查询与患者ID的外部查询相关联(我假设的是pat.pid)。

Select Cast(apt.UniqueID As varchar(36))
    , apt.atime
    , RTRIM(apt.apwork) + ' ' + RTRIM(apt.apwrk2)
    , aps.apsdispchar
    , RTRIM(LTRIM(aps.apstextcolor))
    , RTRIM(LTRIM(aps.apsbgcolor))
    , apT.apid
    , dbo.MakeCaseString(pat.pfname, pat.pfnamcase) + ' ' + dbo.MakeCaseString(pat.plname, pat.plnamcase)
    , apn.apnentrytime
From apt 
    Inner Join pat 
        ON pat.pid = apt.apid 
    Inner Join aps 
        On ((apt.aconfstat Is Not Null And apt.aconfstat = aps.apsid) 
            Or (apt.aconfstat IS NULL And aps.apsid = ' ')) 
    Inner Join apn 
        On (apn.apnpid = apt.apid 
            And apn.apndate = apt.adate 
            And apn.apntime = apt.atime)
Where apt.adid = @ProviderIDParam   
    And apt.adate = @DateParam 
    And apn.apnentrytime IN (   
                            Select Max(APN1.apnentrytime) 
                            From apn As APN1
                                Join apt As APT1
                                    On APT1.apid = APN1.apnpid
                                        And APT1.adate = APN1.apndate
                                        And APT1.atime = APN1.apntime
                            Where APT1.apid = pat.pid
                            )
Order By apt.atime ASC