Q. How can I randomly sort query results?  

  A. To randomly order rows, or to return x number of randomly chosen rows,

   you can use the RAND function inside the SELECT statement.

   But the RAND function is resolved only once for the entire query,

   so every row will get same value.

   You can use an ORDER BY clause to sort the rows by the result from the NEWID function,

   as the following code shows:  

  【对结果记录随机排序,或随机返回X条记录,可以通过在SELECT语句中使用RAND函数来实现。但是RAND函数在查询中只生成一次,因此每一行都将得到相同的值。可以通过在ORDER BY子句中使用NEWID函数来对结果进行排序的方法来实现】


  SELECT * FROM Orders ORDER BY NEWID() ;

  SELECT TOP 10 * FROM Northwind..Orders ORDER BY NEWID() ;

-----------------------------------------------------------------------------------------------------------

找出学生一科成绩最高信息: (要求查询出每个人的最高分. )

表1

ID 姓名 科目 成绩

1 小王 语文 81

2 小王 数学 69

3 小王 英语 67

4 小李 语文 62

5 小李 数学 100

6 小李 英语 60

7 小张 语文 80

8 小张 数学 81

9 小张 英语 77

结果

ID 姓名 科目 成绩

1 小王 语文 81

5 小李 数学 100

8 小张 数学 81

Select a.* from 表1 a,(Select 姓名,max(成绩) 成绩 from 表1 group by 姓名) b where a.姓名=b.姓名 and a.成绩=b.成绩

//思路

先 根据学生分组 找出最高分数 (有可能并列)

Select 姓名,max(成绩) 成绩 from 表1 group by 姓名

再用结果到表1中 用上面的结果作为条件 查询

posted on 2010-03-19 16:29  GT_Andy  阅读(219)  评论(0编辑  收藏  举报