如何根据一组分组数据中的条件检索具有max / min列的行

时间:2019-02-06 12:55:28

标签: android sqlite android-sqlite

我有一个具有以下结构和示例数据的表:

id | date         | nutrient_number | nutrient_goal_value
---------------------------------------------------------
1  | "2019-01-01" | 1               | 5
2  | "2019-01-05" | 1               | 6
3  | "2019-01-06" | 1               | 7
4  | "2019-01-01" | 2               | 20
5  | "2019-01-05" | 2               | 25
6  | "2019-01-06" | 3               | 10
7  | "2019-01-10" | 3               | 8

我需要每个营养编号检索一行,因此在此示例中,我需要返回3行。我的想法是我将按营养素编号分组。

SELECT * from nutrient_goal_table GROUP BY nutrient_number

但是,返回的行必须是我查询的日期(如果存在)之前为最大日期 或<=> 的行,如果不存在不存在,那么它应该是我查询的日期之后最短日期 之后的行。

我可以使它在其中一种条件下工作,就像这样:

SELECT id, MAX(date), nutrient_number, nutrient_goal_value
FROM nutrient_goal_table
WHERE date <= '2019-01-06'
GROUP BY nutrient_number

这将返回:

id | date         | nutrient_number | nutrient_goal_value
---------------------------------------------------------
3  | "2019-01-06" | 1               | 7
5  | "2019-01-05" | 2               | 25
6  | "2019-01-06" | 3               | 10

这很好。但是,如果我必须执行如下查询:

SELECT id, MAX(date), nutrient_number, nutrient_goal_value
FROM nutrient_goal_table
WHERE date <= '2019-01-05'
GROUP BY nutrient_number

当我需要3时,我显然只会得到2个结果。

id | date         | nutrient_number | nutrient_goal_value
---------------------------------------------------------
2  | "2019-01-05" | 1               | 6
5  | "2019-01-05" | 2               | 25

要获得第三个结果,我将需要上述查询来获取我提供的日期之后的最近日期,即,最小日期大于所提供的日期,但只有在不存在包含日期<=提供的日期。

我需要的结果集看起来像这样,提供的日期为'2019-01-05'

id | date         | nutrient_number | nutrient_goal_value
---------------------------------------------------------
2  | "2019-01-05" | 1               | 6
5  | "2019-01-05" | 2               | 25
6  | "2019-01-06" | 3               | 10

我已经花了一段时间的心思,但是我不是很有经验,我正在努力提出解决方案。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

要获取max(date)min(date),可以使用加入约束中的coalesce()

select n.* 
from (SELECT distinct nutrient_number from nutrient_goal_table) d
inner join nutrient_goal_table n
on 
  n.nutrient_number = d.nutrient_number
  and 
  n.date = coalesce( 
    (select max(date) from nutrient_goal_table where date <= '2019-01-05' and nutrient_number = d.nutrient_number),
    (select min(date) from nutrient_goal_table where date >= '2019-01-05' and nutrient_number = d.nutrient_number)
  )

请参见demo

相关问题