我有一个查询,可以通过GrandTotal
选择TOP最高的20%。但有些事情是不公平的。例如,在10个人中排名前20的人之间是2.所以输出结果显示:
EmpName GrandTotal
Kelvin 50
Gem 40
但是第3和第4人的总数也有40人作为总计。我需要一些想法和建议,我将如何解决这个问题?
SELECT TOP 20 PERCENT
EmpName,
SUM(Scoring) AS GrandTotal
FROM
[masterView]
GROUP BY
EmpName
ORDER BY
GrandTotal DESC, EmpName ASC
答案 0 :(得分:1)
在SQL服务器上,您可以使用WITH TIES
来包含关系
SELECT TOP 20 PERCENT WITH TIES Id, sum(Score) as GrandTotal
FROM myTable GROUP BY Id
ORDER BY GrandTotal DESC
答案 1 :(得分:0)
<强> SQL Fiddle Demo 强>
测试数据
CREATE TABLE Table1
([ID] int, [Score] int)
;
INSERT INTO Table1
([ID], [Score])
VALUES
(1, 10), (2, 20),
(3, 30), (4, 20),
(5, 10), (6, 40),
(7, 40), (8, 50),
(9, 10), (10, 5);
<强>查询强>
with ranked as (
select
id,
rank() over (order by Score desc) as rnk
from Table1
),
total as (
select count(*) as total
from Table1
)
SELECT *
FROM ranked
CROSS JOIN total
WHERE ranked.rnk <= 0.2 * total.total
<强>输出强>
| id | rnk | total |
|----|-----|-------|
| 8 | 1 | 10 |
| 6 | 2 | 10 |
| 7 | 2 | 10 |