如何让所有学生知道他们最近的成绩
How to get all students with their recent grades
我的 table 看起来像这样:
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 行。我希望每种类型的 select 行最高 effective_date 所以结果看起来像:
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
怎么做?谢谢
一个选项使用 window 个函数:
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
),则查询 returns 它们全部。
另一种解决方案是相关子查询。这适用于大多数数据库,即使是那些不支持 window 函数的数据库:
select t.*
from mytable t
where t.effective_date = (
select max(t1.effective_date) from mytable t1 where t1.type = t.type
)
我的 table 看起来像这样:
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 行。我希望每种类型的 select 行最高 effective_date 所以结果看起来像:
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
怎么做?谢谢
一个选项使用 window 个函数:
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
),则查询 returns 它们全部。
另一种解决方案是相关子查询。这适用于大多数数据库,即使是那些不支持 window 函数的数据库:
select t.*
from mytable t
where t.effective_date = (
select max(t1.effective_date) from mytable t1 where t1.type = t.type
)