当前位置:网站首页>Sql: median employee salary

Sql: median employee salary

2022-06-09 08:32:00 Jieyou grocery store Q

Employee  Table contains all employees .Employee  The table has three columns : staff Id, Company name and salary .

Id	Company	Salary
1	A	2341
2	A	341
3	A	15
4	A	15314
5	A	451
6	A	513
7	B	15
8	B	13
9	B	1154
10	B	1345
11	B	1221
12	B	234
13	C	2345
14	C	2645
15	C	2645
16	C	2652
17	C	65

 problem :
 Please write SQL Query to find the median salary of each company . Challenge : Whether you can use any built-in SQL Function to solve this problem .

Id	Company	Salary
5	A	451
6	A	513
12	B	234
9	B	1154
14	C	2645

 Insert picture description here

Solution

 Insert picture description here
 Insert picture description here
The difference is less than 1 Is the median

WITH data as (
	SELECT
		id,
		company,
		salary,
		ROW_NUMBER() over(PARTITION by Company ORDER BY Salary desc) rn,
		count(Company) over(PARTITION by company) count
	from Employee
)

SELECT 
	id,
	company,
	salary
FROM data 
where abs(rn - (count+1)/2) < 1

 Insert picture description here

原网站

版权声明
本文为[Jieyou grocery store Q]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090825279682.html