[英]how to do ceil for count of the records and use this number as offset in sql
am new t sql and am trying to solve this Question: Getting the median value from the database am new t sql 并试图解决这个问题: 从数据库中获取中值
I am trying initially to order the table by LAT_N
and then doing offset with the value of the middle, the value of the middle will be the ceil of the number of records divided by two.我最初尝试按
LAT_N
对表进行排序,然后用中间值进行偏移,中间值将是记录数除以二的上限。 so for this I tried:所以为此我尝试了:
select round(LAT_N,4)
from STATION
order by LAT_N desc
limit 1
offset ceil ((select count(LAT_N) from STATION)/2)
but am getting the following error:但出现以下错误:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax;
第 1 行的错误 1064 (42000):您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near '((select count(LAT_N) from STATION)/2)' at line 6
检查与您的 MySQL 服务器版本对应的手册,了解在第 6 行的“((select count(LAT_N) from STATION)/2)”附近使用的正确语法
I am wondering how to retrieve the ceil as a number to use it for offset?我想知道如何将 ceil 检索为数字以将其用于偏移? what did I do wrong?
我做错什么了?
ciel() isn't a MySQL function and it isn't possible to use a subquery as the offset number (sadly) ciel() 不是 MySQL function 并且不可能使用子查询作为偏移量(很遗憾)
You need (it seems) to use dynamic sql to get this to work, eg你需要(似乎)使用动态 sql 来让它工作,例如
SET @table_name:='information_schema.columns';
set @offset := (select cast(count(*)/2 as unsigned) from information_schema.columns);
SET @sql:=CONCAT('SELECT * FROM ',@table_name, ' order by column_name limit 1 offset ',@offset);
select @sql;
PREPARE dynamic_statement FROM @sql;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement;
note you can place the /2 and cast the value to an unsigned integer inside that subquery to calculate the midpoint.请注意,您可以放置 /2 并将该值转换为该子查询内的无符号 integer 以计算中点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.