sqlserver 求平均数,中位数,众数
sqlserver 聚合函数结合 窗口函数的巧妙使用。
SELECT
-- *,
t1.remark,
t1.my_count,
t1.my_sum,
t1.my_avg,
t1.my_min,
t1.my_max,
/*my_median : 中位数*/
t2.my_median,
/*my_most : 众数*/
t3.my_most,
'xxx' AS q
FROM (
SELECT
remark,
COUNT(job_status) AS my_count,
SUM(job_status) AS my_sum,
AVG(job_status) AS my_avg,
MIN(job_status) AS my_min,
MAX(job_status) AS my_max
FROM demo.sys_job_po
GROUP BY
remark
)AS t1
LEFT JOIN
(/*=========中数==================*/
SELECT
remark,
AVG(job_status*1.0) AS my_median
FROM (
SELECT
ROW_NUMBER() OVER(PARTITION BY remark ORDER BY job_status) AS my_row,
COUNT(1) OVER(PARTITION BY remark ) AS my_count,
job_status,
remark
FROM demo.sys_job_po
)AS a
WHERE my_row = my_count/2 +1
OR my_row = (CASE WHEN my_count%2 = 0 THEN my_count/2 ELSE my_count/2 +1 END)
GROUP BY
remark
/*===========================*/
)AS t2 ON t2.remark = t1.remark
LEFT JOIN
(/*=========众数==================*/
SELECT
remark,
my_row,
job_status AS my_most
FROM (
SELECT remark,
ROW_NUMBER() OVER(PARTITION BY remark ORDER BY my_most DESC) AS my_most_row_id,
my_row,
job_status
FROM (
SELECT remark,
ROW_NUMBER() OVER(PARTITION BY remark ORDER BY job_status) AS my_row,
COUNT(job_status) OVER(PARTITION BY remark, job_status) AS my_most,
job_status
FROM demo.sys_job_po
)AS a
)AS b
WHERE my_most_row_id = 1
/*===========================*/
)AS t3 ON t3.remark = t1.remark