Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从两个INT';来自SQL查询的数据是什么?_Sql - Fatal编程技术网

如何从两个INT';来自SQL查询的数据是什么?

如何从两个INT';来自SQL查询的数据是什么?,sql,Sql,我现在正在计算一个数字表的中位数。我相信我计算中位数的代码是正确的,因为我计算中位数的列是一个整数,我得到的答案是一个整数而不是一个浮点。 只是不确定向查询中添加什么以便生成浮点 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 (

我现在正在计算一个数字表的中位数。我相信我计算中位数的代码是正确的,因为我计算中位数的列是一个整数,我得到的答案是一个整数而不是一个浮点。 只是不确定向查询中添加什么以便生成浮点

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
您可以使用
CAST()


请参见

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

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));

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

只是为了强制
浮点
除以
2.0
。MSSQL,很抱歉,对于SQL来说,这是一种全新的方法,而不是如何强制浮点。。。
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));