获取最大值之前的值

发布于 2024-08-21 13:08:50 字数 226 浏览 2 评论 0原文

例如,给定这个稀疏 id 表:

|id|
| 1|
| 2|
| 3|
| 6|
| 7|

我可以使用以下查询从表中获取最高的“id”:

SELECT max(id) FROM Comics

我得到:

|id|
| 7|

如何获取最高“id”之前的“id”(即使这些值是“ t 连续)?

For example, given this table of sparse ids:

|id|
| 1|
| 2|
| 3|
| 6|
| 7|

I can obtain the highest "id" from my table using this query:

SELECT max(id) FROM Comics

I get:

|id|
| 7|

How can I get the "id" just preceding the highest "id" (even if the values aren't continuous)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

衣神在巴黎 2024-08-28 13:08:50

一般来说,您可以首先找到最大 id(您已完成),然后找到小于 (<) 最大值的最大 id。

具体来说,

select max(id) from Comics where id < 7

您也可以按降序对结果进行排序:

select id from Comics order by id desc

然后查看返回的第二行。

In general terms, you could first find the maximum id (which you've done), then find the maximum id that is less than (<) the maximum.

Specifically,

select max(id) from Comics where id < 7

Alternately, you can order the results in descending order:

select id from Comics order by id desc

and then look at the second row returned.

花桑 2024-08-28 13:08:50
SELECT max(id) FROM Comics

与注释相同

SELECT TOP 1 id FROM Comics ORDER BY ID DESC

:这是 transact sql 语法,根据您的供应商使用 rownum 或 limit

来获取您可以执行的第 2 行

SELECT TOP 1 ID 
FROM 
    (SELECT TOP 2 id 
     FROM Comics 
     ORDER BY ID DESC) 
ORDER BY ID ASC
SELECT max(id) FROM Comics

is the same as

SELECT TOP 1 id FROM Comics ORDER BY ID DESC

note: this is transact sql syntax, use rownum or limit depending on your vendor

to get row 2 you can do

SELECT TOP 1 ID 
FROM 
    (SELECT TOP 2 id 
     FROM Comics 
     ORDER BY ID DESC) 
ORDER BY ID ASC
遮了一弯 2024-08-28 13:08:50

这也可以做到..

SELECT
    max(id)
FROM
    Comics 
WHERE id < (SELECT max(id) FROM Comics)

this would do it as well ..

SELECT
    max(id)
FROM
    Comics 
WHERE id < (SELECT max(id) FROM Comics)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文