ugeb
asked on
Accessing variables in MySQL query
I'm not highly skilled in SQL, and my query isn't working, and I'd like to know what I'm doing wrong. I'm trying to write a query in MySQL to calculate a median. My logic is straightforward:
1) Calculate position of median value based on number of entries in table, call this number n.
2) Select the nth row of ordered values in table based on numbering rows with a variable
The first query that calculates the value 'n' works fine. The second query will return all the values as row number and Lat number from the Station table when I set the Where clause to be 'Where 1' instead of what's written below.
The table name is Station and I'm focused on the column named Lat_N.
When I expand the Where clause as written, I get no results. In some variations it complains it doesn't know what rownum is or what n or @n are either, but I'm just trying to figure out this first part.
What would be the proper way to accomplish the task of selecting the nth row as I'm trying to do above?
1) Calculate position of median value based on number of entries in table, call this number n.
2) Select the nth row of ordered values in table based on numbering rows with a variable
The first query that calculates the value 'n' works fine. The second query will return all the values as row number and Lat number from the Station table when I set the Where clause to be 'Where 1' instead of what's written below.
set @n = (SELECT Truncate(Count(S.Lat_N)/2,0) as N FROM STation AS S);
SELECT @rownum:=@rownum+1 as `row_number`, S.Lat_N
FROM Station S, (SELECT @rownum:=0) r
--WHERE 1
WHERE @rownum = @n
ORDER BY S.Lat_N;
The table name is Station and I'm focused on the column named Lat_N.
When I expand the Where clause as written, I get no results. In some variations it complains it doesn't know what rownum is or what n or @n are either, but I'm just trying to figure out this first part.
What would be the proper way to accomplish the task of selecting the nth row as I'm trying to do above?
ASKER
Great, thank you. Can you explain why the subquery is necessary and why my original query didn't work?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Great, thank you for the help.
Open in new window