仅返回具有最大键的行

时间:2018-09-10 09:35:49

标签: sql sql-server tsql select top-n

我的表中有两列:

- RECE_KEY
- INVE_KEY

我只想返回INVE_KEY中RECE_KEY最大的行。

示例:

INVE_KEY = 1包含在RECE_KEY = 1,2,3中。 在此示例中,最大RECE_KEY为3,因此正确的结果为:

+----------+----------+
| RECE_KEY | INVE_KEY |
+----------+----------+
|        3 |        1 |
|        3 |        1 |
|        3 |        1 |
|        3 |        1 |
+----------+----------+

对于整个表格,预期结果将是:

+----------+----------+
| RECE_KEY | INVE_KEY |
+----------+----------+
|        3 |        1 |
|        3 |        1 |
|        3 |        1 |
|        3 |        1 |
|        3 |        4 |
|        5 |        5 |
|        5 |        5 |
|        5 |        5 |
+----------+----------+

我试图解决这种分组问题,但条件不成功。我想我缺少了什么?

下表示例:

DECLARE @JEREIN TABLE
(
RECE_KEY INT,
INVE_KEY INT
)

INSERT INTO @JEREIN 
VALUES(1,1),(1,1),(1,1),(2,1),(2,1),(3,1),(3,1),(3,1),(3,1),(2,4),(2,4),(3,4),(3,5),(3,5),(5,5),(5,5),(5,5)

2 个答案:

答案 0 :(得分:2)

您可以使用rank窗口函数在每个inve_key中找到第一行:

SELECT rece_key, inve_key
FROM   (SELECT rece_key, inve_key, RANK() OVER (PARTITION BY inve_key ORDER BY rece_key DESC) AS rk
        FROM   @JEREIN) t
WHERE  rk = 1

答案 1 :(得分:1)

第一个选择是ranking函数,但是您也可以使用正确的suqbuery:

select t.*
from @JEREIN t
where RECE_KEY = (select max(t1.RECE_KEY) from @JEREIN t1 where t1.INVE_KEY = t.INVE_KEY);

但是,您也可以将dense_rank ties 子句一起使用:

select top (1) with ties t.*
from @JEREIN t
order by dense_rank() over (partition by INVE_KEY order by RECE_KEY desc);