sql - 如何从表格中获得每个类别顶部和底部的总和比率 10%?
问题描述
我有employees
列id
, category
,的表salary
。我想得到每个类别的最高和最低员工的工资比率总和 10%。每个类别的员工数量都不同。
╔══════╤════════╤════════╗
║id │category│salary ║
╠══════╪════════╪════════╣
║102329│1 │8995.00 ║
╟──────┼────────┼────────╢
║102330│2 │10069.00║
╟──────┼────────┼────────╢
║102331│2 │10076.00║
╟──────┼────────┼────────╢
║102332│3 │10516.00║
╟──────┼────────┼────────╢
║102334│3 │9285.00 ║
╟──────┼────────┼────────╢
║102335│3 │9786.00 ║
╟──────┼────────┼────────╢
║102336│1 │9056.00 ║
╟──────┼────────┼────────╢
║102337│4 │5695.00 ║
╟──────┼────────┼────────╢
║102338│4 │5369.00 ║
╟──────┼────────┼────────╢
║102339│3 │10499.00║
╟──────┼────────┼────────╢
║102340│3 │7540.00 ║
╟──────┼────────┼────────╢
║102341│3 │8245.00 ║
╟──────┼────────┼────────╢
║102342│3 │10089.00║
╟──────┼────────┼────────╢
║102343│4 │5631.00 ║
╟──────┼────────┼────────╢
║102344│4 │5674.00 ║
╟──────┼────────┼────────╢
║102345│3 │8607.00 ║
╚══════╧════════╧════════╝
解决方案
您可以使用ntile
将薪水分成十组(十分位数),然后将每个类别顶部和底部的薪水相加:
WITH salaries AS (
SELECT category,
salary
NTILE(10) OVER (PARTITION BY category ORDER BY SALARY asc) AS decile
FROM employees
)
SELECT category,
SUM(salary) FILTER (WHERE decile = 1) /
SUM(salary) FILTER (WHERE decile = 10) AS ratio
FROM salaries
GROUP BY category
推荐阅读
- python - 调用函数时如何修复“标识符中的无效字符”
- laravel - 找不到我的页面,有人可以帮我吗?
- java - 通过 JoranConfigurator 加载 logback-spring.xml 时未读取 springProfile
- git - 将更改和添加的文件从没有工作树的裸仓库导出到目录以进行编译或部署
- r - 如何使用 lappy 进行字符串替换
- node.js - NodeJS 和 ReactJS 的 Heroku 部署
- javascript - 如何让窗口 onunload 事件触发器在 Chrome v73.x 中工作?
- r - 对于具有 dplyr 的其他两个变量的每个唯一组合,仅对分组数据框中的变量求和一次
- c - 如何知道我的程序在运行时实际使用的是哪个共享库?
- django - 为什么我的 Django 应用服务器发送事件端点立即关闭?