Avatar of ugeb
ugeb
Flag 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?
DatabasesMongoDBSQL

Avatar of undefined
Last Comment
ugeb

8/22/2022 - Mon
chaau

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

ugeb

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

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ugeb

ASKER
Great, thank you for the help.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy