【发布时间】:2021-11-05 16:38:44
【问题描述】:
我有一个学生表(id、分数、部门)和部门表(id、名称)。我正在尝试向查询中添加某些条件。
学校部门
+---------+-------------+
| dept_id | name |
+---------+-------------+
| 1 | Admin |
+---------+-------------+
| 2 | Chemistry |
+---------+-------------+
| 3 | Physics |
+---------+-------------+
| 4 | Biology |
+---------+-------------+
| 5 | Mathematics |
+---------+-------------+
学生
+------------+-------+------------+
| student_id | score | department |
+------------+-------+------------+
| 26 | 11 | 4 |
+------------+-------+------------+
| 34 | 11 | 3 |
+------------+-------+------------+
| 76 | 11 | 2 |
+------------+-------+------------+
| 49 | 11 | 1 |
+------------+-------+------------+
| 38 | 11 | 5 |
+------------+-------+------------+
- 选择所有少于 5 名学生的 school_depts
- 按学生总分降序排列学校部门。如果出现平局,则获得该部门最多的学生将是第一;如果仍然存在平局,则应首先使用具有最小 dept_id 的部门。
- 只考虑奇数行,排除偶数行
我的尝试
SELECT * FROM (
SELECT * , ROW_NUMBER() OVER() AS ROW_ID FROM (
SELECT dept_id, name, count(E.student_id) as total_students, SUM(score) as total_score
from Students E
LEFT JOIN school_dept D on dept_id=student_id
group by 1,2
) as O
WHERE total_students<3
order by total_score desc, total_students desc, dept_id asc
) as U
WHERE ROW_ID %2 <>0
预期输出是
name, total_students, total_score
Admin,1,11
Physics1,11
Mathematics,1,11
【问题讨论】:
标签: sql sql-server sorting tsql