我正在尝试将MySQL中的这个中值计算转换为MsSql http://danielsetzermann.com/howto/how-to-calculate-the-median-per-group-with-mysql/
以下是易用性代码
SET @row_number:=0;
SET @median_group:='';
SELECT
median_group, AVG(height) AS median
FROM
(SELECT
@row_number:=
CASE
WHEN @median_group = gender THEN @row_number + 1
ELSE 1
END AS count_of_group,
@median_group:=gender AS median_group,
gender,
height,
(SELECT
COUNT(*)
FROM heights
WHERE a.gender = gender)
AS total_of_group
FROM
(SELECT
gender,
height
FROM heights
ORDER BY gender, height)
AS a)
AS b
WHERE
count_of_group BETWEEN total_of_group / 2.0 AND total_of_group / 2.0 + 1
GROUP BY median_group
就我而言
DECLARE @row_number integer, @median_group varchar(100)
SET @row_number = 0
SET @median_group = ''
SELECT
@row_number = (CASE WHEN @median_group = gender THEN @row_number + 1 ELSE 1 END) AS count_of_group,
(@median_group = gender) AS median_group,
gender,
height,
(SELECT COUNT(*)
FROM heights
WHERE a.gender = gender)
AS total_of_group
FROM
(SELECT
gender,
height
FROM heights)
AS a
ORDER BY a.gender , a.height
可悲的是,我不知道如何克服这个错误 - 一个为变量赋值的SELECT语句不能与数据检索操作结合使用。
非常感谢任何帮助
我知道还有一些其他方法来计算MsSql特定的中位数,但不知道如何让这种转换对我不利。
超级感谢先进
答案 0 :(得分:2)
为什么要在做这样的事情时转换代码呢?
<br>
SQL Server还有许多其他方法可用于此类计算。