sql server—查找表中每个实体的最大n值的最有效的sql查询是什么

nxowjjhe  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(256)

我编写了这两个查询,第一个是保留重复项,第二个是删除它们
有人知道一个更有效的方法来实现这一点吗?
查询是针对mssql的,返回前3个值
1-

SELECT TMP.entity_id, TMP.value
FROM(
    SELECT TAB.entity_id, LEAD(TAB.entity_id, 3, 0) OVER(ORDER BY TAB.entity_id, TAB.value) AS next_id, TAB.value
    FROM mytable TAB
) TMP
WHERE TMP.entity_id <> TMP.next_id

2-

SELECT TMP.entity_id, TMP.value
FROM(
    SELECT TMX.entity_id, LEAD(TMX.entity_id, 3, 0) OVER(ORDER BY TMX.entity_id, TMX.value) AS next_id, TMX.value
    FROM(
        SELECT TAB.entity_id, LEAD(TAB.entity_id, 1, 0) OVER(ORDER BY TAB.entity_id, TAB.value) AS next_id, TAB.value, LEAD(TAB.value, 1, 0) OVER(ORDER BY TAB.entity_id, TAB.value) AS next_value
        FROM mytable TAB
    ) TMX
    WHERE TMP.entity_id <> TMP.next_id OR TMX.value <> TMX.next_value
) TMP
WHERE TMP.entity_id <> TMP.next_id

例子:
表格:

entity_id   value
---------   -----
1           9
1           11
1           12
1           3
2           25
2           25
2           5
2           37
3           24
3           9
3           2
3           15

结果查询1(实体2的25出现两次):

entity_id   value
---------   -----
1           9
1           11
1           12
2           25
2           25
2           37
3           9
3           15
3           24

结果查询2(对于实体2,25只出现一次):

entity_id   value
---------   -----
1           9
1           11
1           12
2           5
2           25
2           37
3           9
3           15
3           24
eyh26e7m

eyh26e7m1#

你可以用 ROW_NUMBER 允许复制如下:

select entity_id, value from
(select t.*, row_number() over (partition  by entity_id order by value desc)  as rn
from your_Table) where rn <= 3

你可以用 rank 按以下步骤删除副本:

select distinct entity_id, value from
(select t.*, rank() over (partition  by entity_id order by value desc)  as rn
from your_Table) where rn <= 3

相关问题