如何从每个类别中选择前 10 条记录

Sha*_*vel 5 sql-server greatest-n-per-group

我有一个带字段的表

Hour,
PathId,
Duration,
Event,
CellId,
Channel
Run Code Online (Sandbox Code Playgroud)

我有 50 多个 CellId。每个 CellId 有四个 PathId(即 0、1、2、3)。每个 PathId 都有许多事件和持续时间。现在我想显示每个 CellId 的前 10 条记录(每个 PathId)。

样品表

样品表

样本输出

样本输出

Mik*_*son 14

在派生表中使用row_number()CellID根据您的规范进行分区和使用 order by。在主查询中,您可以过滤rn以获取每个类别的前 10 行。

select T.CellID,
       T.PathID,
       T.Duration
from (
     select T.CellID,
            T.PathID,
            T.Duration,
            row_number() over(partition by T.CellID order by T.Duration desc) as rn
     from dbo.YourTable as T
     ) as T
where T.rn <= 10;
Run Code Online (Sandbox Code Playgroud)