SELECT TOP 20%SQL

时间:2015-11-14 02:37:26

标签: sql

我有一个查询,可以通过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

2 个答案:

答案 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 |