来自以下的Mysql查询
select (
case
when grade < 8 then null
else name
end
) as name,
grade, marks
from students
join Grades
ON Min_mark = (SELECT MAX(Min_mark) from grades where min_mark <= students.marks)
order by grade desc,name asc
我想根据等级的值对订单进行排序,即
生成包含三列的报告:名称,成绩和标记。报告必须按等级降序排列 - 即首先输入更高的等级。如果分配了相同年级(1-10)的学生不止一个,请按字母顺序按名称命名这些学生。最后,如果等级低于8,请使用&#34; NULL&#34;作为他们的名字,并按他们在升序中的标记列出
select (
case
when grade < 8 then null
else name
end
) as name,
grade, marks
from students
join Grades
ON Min_mark = (SELECT MAX(Min_mark) from grades where min_mark <= students.marks)
case
when grade <8 then
order by grade desc, name asc
else
order by marks asc
end
但由于语法错误,第二个查询无法执行。有人可以建议我如何获得所需的结果。在此先感谢
答案 0 :(得分:1)
我的猜测是这样的:
ORDER BY grade > 10 DESC /* orders by grade>10 records first */
, CASE WHEN grade > 10 THEN grade ELSE null END DESC /* all grade<=10 records will "sort" equally among themselves */
, CASE WHEN grade > 10 THEN name ELSE marks END ASC /* all grade<=10 records will "sort" by `name`, others will sort my `marks` */
答案 1 :(得分:1)
不可能通过两个不同的order by子句对查询进行排序。
您可以在语句中添加一个或多个其他行,并按此行排序。 要做到这一点,你必须决定如何排序。如果等级低于10,则所有等级之前的等级> 10?
这样的事情可行:
select (
case
when grade < 8 then null
else name
end
) as name,
grade, marks,
(
case
when grade > 10 then grade
else null
end
) as sortorder1,
(
case
when grade > 10 then name
else marks
end
) as sortorder2
from students
join Grades
ON Min_mark = (SELECT MAX(Min_mark) from grades where min_mark <= students.marks)
order by sortorder1 desc, sortorder2 asc
编辑低于8的成绩也应按成绩排序:
我认为这应该有效:
select (
case
when grade < 8 then null
else name
end
) as displayname,
grade, marks
from students
join Grades
ON Min_mark = (SELECT MAX(Min_mark) from grades where min_mark <= students.marks)
order by grade desc, displayname asc, marks asc
我将&#39;替换为名称&#39;由&#39;作为显示名称&#39;为了更清楚,排序应该通过displayname来完成,我不确定数据库是否需要这样做,但对于阅读查询的人来说更清楚。
答案 2 :(得分:1)
我不知道你的专栏名称,但对我而言,这应该是这么简单:
select IF(grade < 8, null, grade) as processed_grade, name
from students
join Grades
ON students.id = Grades.id_student
order by processed_grade desc,name asc
如果低于8,您只需将成绩更改为null,然后按此新创建的列和名称对记录进行排序。