2017-04-24 49 views
0

我已經從一個大型數據庫中創建了一個臨時表,我必須計算該臨時表。如何計算返回查詢的MySQL臨時表的中位數

下面創建臨時表的代碼(它有21行與數字第一卷)

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

下面的代碼計算中位數,但沒有得到如何做到這一點上面創建的臨時表「表1」

SELECT AVG(middle_values) AS 'median' FROM (
SELECT t1.`vol` AS 'middle_values' FROM 
(
    SELECT @row:[email protected]+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; 

如果我使用下面的代碼與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

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:[email protected]+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; 

非常感謝您的幫助。

+0

嘗試用圓括號替換第二個select語句(union all運算符後面的那個)。 –

回答

0

解決了......對於偶數和奇數都有正確的答案。

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; 

感謝您的回覆。

相關問題