简体   繁体   中英

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.

below code for creating temporary table (It has 21 rows of vol with numbers)

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"

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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