Sql 如何让所有学生了解他们最近的成绩
我的桌子是这样的:Sql 如何让所有学生了解他们最近的成绩,sql,datetime,subquery,greatest-n-per-group,Sql,Datetime,Subquery,Greatest N Per Group,我的桌子是这样的: 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
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
怎么做?谢谢。一个选项使用窗口功能:
select *
from (
select t.*, rank() over(partition by type order by effective_date desc) rn
from mytable t
) t
where rn = 1
select t.*
from mytable t
where t.effective_date = (
select max(t1.effective_date) from mytable t1 where t1.type = t.type
)
如果存在顶部关系(即,两行或更多行具有相同的类型和最大生效日期),则查询将返回所有这些关系
另一个解决方案是相关子查询。这适用于大多数数据库,即使是不支持窗口功能的数据库:
select *
from (
select t.*, rank() over(partition by type order by effective_date desc) rn
from mytable t
) t
where rn = 1
select t.*
from mytable t
where t.effective_date = (
select max(t1.effective_date) from mytable t1 where t1.type = t.type
)
一个选项使用窗口功能:
select *
from (
select t.*, rank() over(partition by type order by effective_date desc) rn
from mytable t
) t
where rn = 1
select t.*
from mytable t
where t.effective_date = (
select max(t1.effective_date) from mytable t1 where t1.type = t.type
)
如果存在顶部关系(即,两行或更多行具有相同的类型和最大生效日期),则查询将返回所有这些关系
另一个解决方案是相关子查询。这适用于大多数数据库,即使是不支持窗口功能的数据库:
select *
from (
select t.*, rank() over(partition by type order by effective_date desc) rn
from mytable t
) t
where rn = 1
select t.*
from mytable t
where t.effective_date = (
select max(t1.effective_date) from mytable t1 where t1.type = t.type
)
学生在哪里?学生在哪里?我无法验证这个答案,但窗口函数看起来是一个不错的方法。我无法验证这个答案,但窗口函数看起来是一个不错的方法。