【发布时间】:2015-12-08 09:01:07
【问题描述】:
我在过滤查询返回的结果行方面需要帮助。我有一个 Illnesses 表,其中包含 percent、illness、date 列。
SELECT I.percent, I.illness, I.date
FROM Illnesses I
INNER JOIN Person P on I.person_id = P.id // an inner join I use in where clause
WHERE P.id = someId // 13 let's say
所以在我的情况下,对于 id = 13 的 Person 查询将返回
51, someIllness, 2015-12-07
43,someOtherIllness, 2015-12-08
null, anotherIllness, 2015-12-08
我需要选择 date 是最近的行,如果有多行具有该日期,则选择最高的 percent。我在 where 子句中添加了以下代码
AND I.date = (SELECT max(I2.date)
FROM Illnesess I2
INNER JOIN Person P2 on I2.person_id = P2.id
WHERE P2.id = P.id)
AND I.percent = (SELECT max(I2.percent)
FROM Illnesess I2
INNER JOIN Person P2 on I2.person_id = P2.id
WHERE P2.id = P.id AND I2.date = I.date)
这将返回 43,someOtherIllness, 2015-12-08 并且至少我认为可以正常工作。我需要说明一个例外情况,如果最近日期的百分比为 null,我需要使用具有百分比的前一个日期的行。
51, someIllness, 2015-12-07
null,someOtherIllness, 2015-12-08
null, anotherIllness, 2015-12-08
51, someIllness, 2015-12-07 将是我需要的结果。
如果有人提供帮助,我将不胜感激。谢谢。
【问题讨论】:
-
您使用的是哪个 DBMS?
-
我正在使用 postgreSQL
标签: sql postgresql greatest-n-per-group