按 SQL 中 SELECT 中未指定的列对 SELECT 查询进行排序

Order a SELECT query by a column not specified in the SELECT in TSQL

我在 MS SQL Server 2016 中使用此查询:

select MAX(DATEADD(s, timecreated, '19700101 02:00:00')) AS last_active_on, courseid
from mdl_logstore_standard_log
where eventname = '\core\event\course_viewed'
group by courseid
order by last_active_on desc, courseid;

获取 Moodle 中最近访问的课程列表:

last_active_on courseid
2021-12-07 15:00:33.000 11450
2021-12-07 15:00:27.000 11365
2021-12-07 15:00:10.000 11363
2021-12-07 15:00:02.000 11068
2021-12-07 14:59:55.000 11430
2021-12-07 14:59:46.000 11171
2021-12-07 14:59:38.000 11413
2021-12-07 14:58:20.000 11362
2021-12-07 14:58:07.000 1
2021-12-07 14:56:36.000 11268

但是,我只想要“'courseid'”列,如下所示:

courseid
11450
11365
11363
11068
11430
11171
11413
11362
1
11268

当我使用“order by last_active_on desc, courseid;"?

(timecreated 列包含一个 unix 时间戳,因此我使用 dateadd() 将其格式化为“正常”日期。)

用表达式替换 ORDER BY 中的别名,并从 SELECT 之后的列表中删除表达式。

SELECT courseid
       FROM mdl_logstore_standard_log
       WHERE eventname = '\core\event\course_viewed'
       GROUP BY courseid
       ORDER BY max(dateadd(s, timecreated, '19700101 02:00:00')) DESC,
                courseid ASC;

可以使用列位置

例如:

ORDER BY 1