mysql到mssql的转换(中间值)

gk7wooem  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(418)

我正在尝试将mysql中的中值计算转换为mssqlhttp://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特定的,但不知道如何进行这种转换是吃我。
非常感谢您的光临

c6ubokkw

c6ubokkw1#

既然你能做这样的事情,为什么还要转换代码呢?

select distinct gender, percentile_cont(0.5) over (partition by gender order by height)
from heights;

SQLServer有许多其他方法来进行这种计算。

相关问题