【发布时间】:2022-01-13 13:25:36
【问题描述】:
我有一个名为 grade 的表,有 4 列:student_id、subject_id、grade 和 date。
| student_id | subject_id | grade | date |
|---|---|---|---|
| Jenny | math | 90 | 2021-12-08 |
| Susan | math | 60 | 2021-12-08 |
| Jenny | math | 80 | 2021-12-07 |
| Susan | math | 50 | 2021-12-07 |
| Jenny | science | 80 | 2021-12-08 |
| Susan | science | 90 | 2021-12-08 |
| Jenny | science | 76 | 2021-12-06 |
| Susan | science | 85 | 2021-12-06 |
我想选择所有行,其中只有每个学生的每个科目的最后一个年级。基本上,我想选择所有具有唯一student_id、subject_id 的行,如下所示:
| student_id | subject_id | grade | date |
|---|---|---|---|
| Jenny | math | 90 | 2021-12-08 |
| Susan | math | 60 | 2021-12-08 |
| Jenny | science | 80 | 2021-12-08 |
| Susan | science | 90 | 2021-12-08 |
这是我尝试过的:
await Grade.findAll({
attributes: ['student_id', 'subject_id', 'grade', 'date'],
raw: true,
group: ['student_id', 'subject_id']
})
但是,我收到以下错误:
SequelizeDatabaseError: column "grade.grade" must appear in the GROUP BY clause or be used in an aggregate function
【问题讨论】:
-
我不知道如何在 Sequelize.JS 中编写,但在 postgres 中,您需要在 (student_id 和 subject_id ) 上按日期 DESC 顺序使用窗口函数和
标签: sql node.js postgresql sequelize.js