如何从SQL查询中返回两个INT的FLOAT?

时间:2014-08-08 03:13:11

标签: sql

我目前正在计算数字表的中位数。我相信我的计算中位数的代码是正确的,但因为我正在计算它的列是一个INT我得到的答案是INT而不是FLOAT。 只是不确定要添加到查询中的内容,以便生成FLOAT ...

CREATE TABLE q4(
 Month      INT,
 Score      INT)

 INSERT INTO q4(Month, Score)
 VALUES (1,10), (2,5), (7,2), (8,6), (1,9), (4,11), (5,3), (9,10);


SELECT
(
 (SELECT MAX(Score) FROM
 (SELECT TOP 50 PERCENT Score FROM q4 ORDER BY Score) AS BottomHalf) 
 +
 (SELECT MIN(Score) FROM
 (SELECT TOP 50 PERCENT Score FROM q4 ORDER BY Score DESC) AS TopHalf)
) / 2 AS Median

2 个答案:

答案 0 :(得分:0)

您可以使用CAST()

SELECT
CAST((
(
 (SELECT CAST(MAX(Score) as float) FROM
 (SELECT TOP 50 PERCENT Score FROM q4 ORDER BY Score) AS BottomHalf) 
 +
 (SELECT CAST(MIN(Score) as float) FROM
 (SELECT TOP 50 PERCENT Score FROM q4 ORDER BY Score DESC) AS TopHalf)
) / 2) as decimal(5,2)) AS Median

参见 Demo

答案 1 :(得分:0)

计算中位数的方法需要对数据进行两次排序。这是另一种方法:

select avg(cast(score as float)) as median
from (select q.*, row_number() over (order by score) as seqnum,
             count(*) over () as cnt
      from q4 q
     ) q
where (cnt % 2 = 1 and seqnum * 2 = (cnt + 1) or
       cnt % 2 = 0 and seqnum * 2 in (cnt - 1, cnt + 1));

当行数为奇数时选择一个值,当行数为偶数时选择两个值。你的方法也有效。我只是建议将其作为一种替代方案,不需要对数据进行两次排序。