首页 > 解决方案 > 如何从表格中获得每个类别顶部和底部的总和比率 10%?

问题描述

我有employeesid, 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 ║
╚══════╧════════╧════════╝

标签: sqlpostgresqlselect

解决方案


您可以使用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

推荐阅读