【问题标题】:How to get all students with their recent grades如何让所有学生知道他们最近的成绩
【发布时间】:2020-10-29 22:09:52
【问题描述】:

我的桌子是这样的:

id | type    | price    | effective_date 
1  | a       | 0.05     | 2020-12-15
2  | b       | 0.05     | 1990-11-15
3  | c       | 0.05     | 1990-02-15
4  | d       | 0.05     | 1990-05-15
5  | a       | 0.05     | 2001-01-04
6  | b       | 0.05     | 1990-02-12
7  | a       | 0.05     | 2004-02-11
8  | a       | 0.05     | 2054-02-07

所以我有 4 种类型(a、b、c、d)和 8 行。我想为每种类型选择具有最高有效日期的行,因此结果如下所示:

id | type    | price    | effective_date
8  | a       | 0.05     | 2054-02-07
2  | b       | 0.05     | 1990-11-15
3  | c       | 0.05     | 1990-02-15
4  | d       | 0.05     | 1990-05-15

怎么做?谢谢。

【问题讨论】:

  • 那里的学生在哪里?

标签: sql datetime subquery greatest-n-per-group


【解决方案1】:

一个选项使用窗口函数:

select *
from (
    select t.*, rank() over(partition by type order by effective_date desc) rn
    from mytable t
) t 
where rn = 1

如果存在最高关联(即两行或多行具有相同的type 和最大的effective_date),则查询将全部返回。

另一种解决方案是相关子查询。这适用于大多数数据库,即使是那些不支持窗口函数的数据库:

select t.*
from mytable t
where t.effective_date = (
    select max(t1.effective_date) from mytable t1 where t1.type = t.type
)

【讨论】:

  • 我无法验证这个答案,但窗口函数看起来不错。
猜你喜欢
  • 1970-01-01
  • 2013-02-10
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 2021-09-18
  • 1970-01-01
相关资源
最近更新 更多