SQL 有条件的分组

SQL GROUPING with conditional

我相信这很容易完成,但在花了一整天的时间尝试后我不得不放弃并寻求你的帮助。

我有一个 table 看起来像这样

| PatientID  | VisitId  | DateOfVisit  | FollowUp(Y/N) | FollowUpWks |
----------------------------------------------------------------------
| 123456789  | 2222222  |  20180802    |     Y         |     2       |
| 123456789  | 3333333  |  20180902    |     Y         |     4       |
| 234453656  | 4443232  |  20180506    |     N         |    NULL     |
| 455344243  | 2446364  |  20180618    |     Y         |    12       |
----------------------------------------------------------------------

基本上我有一个 PatientIDs 列表,每个患者可以有多次就诊(VisitID 和 DateOfVisit)。 FollowUp(Y/N) 指定是否必须再次看到患者以及在多少周 (FollowUpWks)。

现在,我需要的是提取 PatientsID、DateOfVisit(最近的一个并且仅当 FollowUp 为 YES 时)和 FollowUpWks 字段的查询。

最终结果应该是这样的

| PatientID  | VisitId  | DateOfVisit  | FollowUp(Y/N) | FollowUpWks |
----------------------------------------------------------------------
| 123456789  | 3333333  |  20180902    |     Y         |     4       |
| 455344243  | 2446364  |  20180618    |     Y         |    12       |
----------------------------------------------------------------------

我能得到的最接近的是这个代码

SELECT PatientID,
       Max(DateOfVisit) AS LastVisit
FROM mytable
WHERE FollowUp = True
GROUP BY PatientID;

问题是,当我尝试将 FollowUpWks 字段添加到 SELECT 时,我收到以下错误:"The query does not include the specified expression as part of an aggregate function." 但是,如果我将 FollowUpWks 添加到 GROUP BY 语句,我将获得所有访问,不仅仅是最近的。

您需要匹配回最近的访问。一种方法使用相关子查询:

SELECT t.*
FROM mytable as t
WHERE t.FollowUp = True AND
      t.DateOfVisit = (SELECT MAX(t2.DateOfVisit)
                       FROM mytable as t2
                       WHERE t2.PatientID = t.PatientID
                      );