Friday, March 30, 2012

How can I request row #3 in a dataset?

I've got a table that houses the data for several routes, (routeID, pointID, Longitude, Latitude and Elevation). a set of Points make up a route. I'd like to programmatically access specific points and I'm trying to figure out how to request...say the third point in my dataset. I'm new to SQL, but I was able to figure out that I can find the row number by using the SQL syntax:

SELECT ROW_NUMBER()OVER(ORDER by PointID)as'Num', Latitude, Longitude, ElevationFROM [PointTable]WHERE (RouteID = 5)

But I cannot (or do not know how to) add a clause that says

AND (Num = 3)
So can someone show me how to request a specific row?

It's really easy, and the trick to it will serve you in good stead in many other situations.

When you issue a select statement, you are selecting "from" something. That something might be a table, or it might be a view.

But what IS a view? It's a query that's given a name, an alias if you will. When a view is used, the actual query statement it represents is substituted for the view's name in the sql statement as part of the parsing process.

How does that knowledge help?

Because you don't have to bother to give a view a name, you can just fill in a query for yourself. Just pop in inside a set of parentheses and supply an alias

So:

SELECT *

FROM

(

SELECT ROW_NUMBER()OVER(ORDER by PointID)as'Num', Latitude, Longitude, Elevation
FROM [PointTable]
WHERE (RouteID = 5)
) AS temporary_result_set
WHERE temporary_result_set.Num = 3
 


|||WOW! Thank you David, that did the trick. You're explaination just doubled my understanding on how T-SQL works and got my mind thinking of other things to try.

No comments:

Post a Comment