问题描述
[size=xx-large]一个学生表stu,有中学生和小学生,记录考试成绩,现在要查出成绩最高的10名中学生和10名小学生,怎么写sql?select top(10) * from stu where type=中 order by score descunionselect top(10) * from stu where type=小 order by score desc这样会报错, 那恰当的写法是怎样的呢?sql server环境下.[/size]
解决方案
http://www.codesky.net/article/201007/145530.htmlselect * from ( select top(10) * from stu where type=中 order by score desc ) t1union allselect * from ( select top(10) * from stu where type=小 order by score desc ) t2union all--代替union (因为union会排序 但此处没必要 )你这个逻辑有问题 假设前10名的成绩为100100100999999989898979797 (这个也算吧) 可以这样select * from stu where type=中 and score in ( select top 10 score from stu where type=中 group by score order by score)
解决方案二:
union 要确保2边的列是一样多,也就 a union b 那么a 要查询3列,b也要查询3列,
时间: 2024-10-29 10:52:55