简体   繁体   English

如何计算返回的查询MySQL临时表的中位数

[英]how to calculate median for a returned queried MySQL temporary table

I have created a temporary table from a big database for which I have to calculate medain. 我已经从一个大型数据库创建了一个临时表,必须为此数据库计算medain。

below code for creating temporary table (It has 21 rows of vol with numbers) 下面的代码用于创建临时表(它具有21行的数字行)

CREATE TEMPORARY TABLE table1 (Select vol from EOD_PRICING where 
`ticker`=16665396 order by `xdate` desc limit 21);    

below code to calculate median but not getting how to do it for above created temporary table "table1" 下面的代码来计算中位数,但无法获得上面创建的临时表“ table1”的处理方法

SELECT AVG(middle_values) AS 'median' FROM (
SELECT t1.`vol` AS 'middle_values' FROM
(
  SELECT @row:=@row+1 as `row`, x.`vol`
  FROM table1 AS x, (SELECT @row:=0) AS r
  WHERE `ticker`=16665396 order by `xdate` desc limit 21
  ORDER BY x.`vol`
) AS t1,
(
  SELECT COUNT(*) as 'count'
  FROM table1 x
  WHERE `ticker`=16665396 order by `xdate` desc limit 21
) AS t2
WHERE t1.row >= t2.count/2 and t1.row <= ((t2.count/2) +1)) AS t3;

If I use below code with UNION ALL for my requirement it says You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 17 如果我将下面的代码与UNION ALL一起使用以满足我的要求,它会说You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 17 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 17

CREATE TEMPORARY TABLE table1 (Select * from EOD_PRICING where 
`ticker`=16665396 order by `xdate` desc limit 21)
UNION ALL
SELECT AVG(middle_values) AS 'median' FROM (
SELECT t1.`vol` AS 'middle_values' FROM
(
  SELECT @row:=@row+1 as `row`, x.`vol`
  FROM table1 AS x, (SELECT @row:=0) AS r
  ORDER BY x.`vol`
) AS t1,
(
  SELECT COUNT(*) as 'count'
  FROM table1 x
) AS t2
WHERE t1.row >= t2.count/2 and t1.row <= ((t2.count/2) +1)) AS t3;

Thanks in advance for helping out. 在此先感谢您的帮助。

Solved...got right answer for both even and odd. 解决了...对偶数和奇数都有正确的答案。

SELECT AVG( middle_values ) AS 'median'
FROM (

SELECT t1.`vol` AS 'middle_values'
FROM (

SELECT @row := @row +1 AS `row` , x.`vol` 
FROM (

SELECT * 
FROM EOD_PRICING
WHERE `ticker` =16665396
ORDER BY `xdate` DESC 
LIMIT 22
) AS x, (

SELECT @row :=0
) AS r
ORDER BY x.`vol`
) AS t1, (

SELECT COUNT( * ) AS 'count'
FROM (

SELECT * 
FROM EOD_PRICING
WHERE `ticker` =16665396
ORDER BY `xdate` DESC 
LIMIT 22
) AS x
) AS t2
WHERE t1.row >= t2.count /2
AND t1.row <= ( (
t2.count /2
) +1 )
) AS t3;

Thanks for replies. 感谢您的答复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM