使用 SQL 根据状态对两个表进行子查询

Sub query for two tables base on status using SQL

我有两个 tables Patient 和 PatientStatusLog 使用 SQL tables

1.Patient

sno   patientid   status      createdby   Reegion
 1     481910      D             1222     India
 2     476795      D             1222     India

2.PatientStatusLog

sno     patientid   status           comments       createdby     CreatedDate(dd/mm/yyyy)
1       481910      A                mycommnet       1222         01/01/2000
2       481910      A                mycommnet       1222         02/01/2000      
3       481910      B                mycommnet       1222         01/01/2000
4       481910      C                mycommnet       1222         01/01/2000

我需要像下面这样的输出,他们的状态为 A,创建日期应该是 PatientStatusLog table 的最近通过日期,使用 tables

的 patientid
Region    status     CreatedDate
India      A         02/01/2000

试试这个:

SELECT TOP 1
    p.Region,
    psl.Status,
    psl.CreatedDate
FROM
    Patient [p]
    JOIN PatientStatusLog [psl] ON psl.patientid = p.patientid
        AND psl.status = 'A'
ORDER BY
    psl.CreatedDate DESC

对于子查询请求:

SELECT
    p.Region,
    x.status,
    x.CreatedDate
FROM
(
    SELECT TOP 1
        PatientId,
        Status,
        CreatedDate
    FROM
        PatientStatusLog
    WHERE
        status = 'A'
    ORDER BY 
        CreatedDate DESC
) AS x
    JOIN Patient [p] ON p.PatientId = x.PatientId

请注意,从代码可读性和优化的角度来看,这绝对不是处理此问题的最佳方法。

您可以使用 window 函数:

select . . .    -- whatever columns you want
from Patient p join
     (select psl.*,
             rank() over (partition by patientid order by createddate desc) as seqnum
      from PatientStatusLog psl
     ) psl
     on p.patientid = psl.patientid
where psl.seqnum = 1 and psl.status = 'A';

请注意,这里使用 rank(),因为创建日期似乎有重复。