根据最大值过滤 SQL 服务器数据
Filter SQL Server data according to its max value
我有一个 SQL Server 2008 table 喜欢:
+------+-------+--------------------------------------+
| id | level | content |
+------+-------+--------------------------------------+
| 1 | 1 | ... |
| 2 | 2 | ... |
| 1 | 2 | ... |
| 1 | 3 | ... |
| 2 | 1 | ... |
| 1 | 4 | ... |
| 3 | 1 | ... |
+------+-------+--------------------------------------+
对于每个id,它可能像上面那样在table中保存了三层、两层或四层。如何获取每个 id 的数据:
- 每个id最后最多有3条记录table
- 如果一个id的max level大于3,则三个record的level为max到max-3;
- 如果一个id的最高等级等于或小于3,就保持原样。
所以我想要得到的最终 table 是:
+------+-------+--------------------------------------+
| id | level | content |
+------+-------+--------------------------------------+
| 1 | 1 | ... |
| 2 | 2 | ... |
| 1 | 2 | ... |
| 1 | 3 | ... |
| 2 | 1 | ... |
| 3 | 1 | ... |
+------+-------+--------------------------------------+
我怎么能行呢?非常感谢。
我想你想要每个 id
的 3 个最新的 level
。如果是这样,您可以像这样使用 window 函数:
select *
from (
select t.*, row_number() over(partition by id order by level desc) rn
from mytable t
) t
where rn <= 3
我有一个 SQL Server 2008 table 喜欢:
+------+-------+--------------------------------------+
| id | level | content |
+------+-------+--------------------------------------+
| 1 | 1 | ... |
| 2 | 2 | ... |
| 1 | 2 | ... |
| 1 | 3 | ... |
| 2 | 1 | ... |
| 1 | 4 | ... |
| 3 | 1 | ... |
+------+-------+--------------------------------------+
对于每个id,它可能像上面那样在table中保存了三层、两层或四层。如何获取每个 id 的数据:
- 每个id最后最多有3条记录table
- 如果一个id的max level大于3,则三个record的level为max到max-3;
- 如果一个id的最高等级等于或小于3,就保持原样。
所以我想要得到的最终 table 是:
+------+-------+--------------------------------------+
| id | level | content |
+------+-------+--------------------------------------+
| 1 | 1 | ... |
| 2 | 2 | ... |
| 1 | 2 | ... |
| 1 | 3 | ... |
| 2 | 1 | ... |
| 3 | 1 | ... |
+------+-------+--------------------------------------+
我怎么能行呢?非常感谢。
我想你想要每个 id
的 3 个最新的 level
。如果是这样,您可以像这样使用 window 函数:
select *
from (
select t.*, row_number() over(partition by id order by level desc) rn
from mytable t
) t
where rn <= 3