我第一次使用SAP HANA。以下是我计算视图的一些示例数据。我想要的结果是计算后的最后一位老师。
我有2个学生。有一个学生最后一次见过老师的日期。对于每个学生,我想用sql语句计算上次见过的老师。有什么想法吗?
答案 0 :(得分:0)
在目前不支持窗口功能的MySQL中,你可以试试这个:
SELECT
t1.*,
t3.TeacherID AS last_teacher
FROM yourTable t1
INNER JOIN
(
SELECT studentID, MAX(LastSeen) AS max_last_seen
FROM yourTable
GROUP BY studentID
) t2
ON t1.studentID = t2.studentID
INNER JOIN yourTable t3
ON t2.studentID = t3.studentID AND
t2.max_last_seen = t3.LastSeen;
使用窗口函数,我们可以取消其中一个连接,并稍微简化以下内容:
SELECT
t1.StudentID,
t1.TeacherID,
t1.LastSeen,
t2.TeacherID AS last_teacher
FROM
(
SELECT StudentID, TeacherID, LastSeen,
MAX(LastSeen) OVER (PARTITION BY StudentID) AS max_last_seen
FROM yourTable
) t1
INNER JOIN yourTable t2
ON t1.StudentID = t2.StudentID AND
t1.max_last_seen = t2.LastSeen;
答案 1 :(得分:0)
尝试以下查询。
SELECT *
FROM table
WHERE last_seen IN (
SELECT Max(last_seen)
FROM table
GROUP BY student_id
)
答案 2 :(得分:0)
您可以使用Row_Number()
函数在oracle
db中按列获取LastRecord,如下所示:
Select * from
(
select
ROW_NUMBER() OVER (PARTITION BY studentId ORDER BY LastSeen desc) as rn,
studentId,
TeacherId
from yourTable
)
where rn = 1;
此功能将每个studentId
分组,并为每个studentIdGroup按LastSeen
列排序。然后,您可以使用where语句where rn = 1
<强>更新强> 如果你想要选择表格中的所有行,那么你可以将这个选择声明加入你的表格,如下所示:
select * from yourTable t
join
(
Select * from
(
select
ROW_NUMBER() OVER (PARTITION BY studentId ORDER BY LastSeen desc) as rn,
studentId,
TeacherId
from yourTable
)
where rn = 1
) s
on t.studentId = s.studentId;