【问题标题】:SQL query filtering returnd rows by conditionsSQL查询按条件过滤返回的行
【发布时间】:2015-12-08 09:01:07
【问题描述】:

我在过滤查询返回的结果行方面需要帮助。我有一个 Illnesses 表,其中包含 percentillnessdate 列。

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


【解决方案1】:

如果你从一开始就删除所有没有百分比的疾病?

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
AND I.percent IS NULL

【讨论】:

    【解决方案2】:

    你可以试试这个

    SELECT I.percent, I.illness, I.date 
    FROM Illnesses I
    INNER JOIN Person P on I.person_id = P.id
    WHERE I.percent IS NOT NULL 
    ORDER BY I.date, I.percent DESC
    LIMIT 1
    

    如果您希望它首先按最高百分比排序,您可以尝试在顺序中交换日期和百分比位置

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 2019-01-14
      • 2012-01-08
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2020-04-21
      相关资源
      最近更新 更多