Friday, December 14, 2007

How to select the top 10 records by using SQL?

How to select the top 10 records by using SQL?

When using SQL to get a set of record which you only need the first few records; we can use TOP command in the SQL to get few records at the top:

<%

Set conn = Server.CreateObject("Adodb.Connection")

conn.Open "Driver={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath("db1.mdb")

Set rs = Server.CreateObject("Adodb.Recordset")

strSQL = "SELECT Top 2 * FROM Member" 'Generate a SQL command to get the top 2 records.

rs.Open strSQL,conn,1,3 'Use the SQL to generate the Recordset

Do while Not rs.eof

Response.Write(rs("MemberName") & "
")

rs.movenext

Loop

rs.Close

Set rs = Nothing

%>

We can also select the percentage of the record that is needed to show.


For example:

SELECT Top 10 Percent * FROM Stocks Order By Price DESC

* Query the top 10 percent record that the price is high.


No comments: