MS Access在表中选择第N个最高值

时间:2018-08-09 09:26:26

标签: sql database ms-access

所以我有以下数据库格式:

+------++------+
| ID   | Value |
+------++------+ 
| 1    |   5   |
| 1    |   2   |
| 1    |   8   |
| 1    |   1   |
| 2    |   2   |
| 2    |   3   |
| 2    |   6   |
| 2    |   10  |
| 3    |   1   |
| 3    |   2   |
| 3    |   5   |
| 3    |   3   | 
| 3    |   5   |
+------++------+

我正在尝试输出每个ID的前3个值。喜欢:

    +------++------+
    | ID   | Value |
    +------++------+ 
    | 1    |   8   |
    | 1    |   5   |
    | 1    |   3   |
    | 2    |   10  |
    | 2    |   6   |
    | 2    |   3   |
    | 3    |   5   |
    | 3    |   5   |
    | 3    |   3   |
    +------++------+

使用SQL在MS Access中可以做到吗?

1 个答案:

答案 0 :(得分:2)

您需要 correlation 子查询:

select t.*
from [table] t
where value in (select top 3 t1.value
                from [table] t1
                where t1.id = t.id
                order by t1.value desc
               ) order by ID asc, value desc;