Link to home
Start Free TrialLog in
Avatar of ugeb
ugebFlag for United States of America

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.

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;

Open in new window


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?
Avatar of chaau
chaau
Flag of Australia image

You need to use a subquery for this:

set @n = (SELECT Truncate(Count(S.Lat_N)/2,0) as N FROM STation AS S);
SELECT * FROM(
SELECT @rownum:=@rownum+1 as `row_number`, S.Lat_N
  FROM Station S,  (SELECT @rownum:=0) r
--WHERE 1
  ORDER BY S.Lat_N) as a
  WHERE row_number = @n;

Open in new window

Avatar of ugeb

ASKER

Great, thank you.  Can you explain why the subquery is necessary and why my original query didn't work?
ASKER CERTIFIED SOLUTION
Avatar of chaau
chaau
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ugeb

ASKER

Great, thank you for the help.