【问题标题】:How to return "row number" of first occurrence, SQL?如何返回第一次出现的“行号”,SQL?
【发布时间】:2010-08-27 09:11:55
【问题描述】:
                         (row number not stored in db)

------------------------
|      |     A   |     | (1)
------------------------
|      |     B   |     | (2)
------------------------
|      |     C   |     | (3)
------------------------ -----Page 1
|      |     D   |     | (4)
------------------------
|      |     E   |     | (5)
------------------------
|      |     F   |     | (6)
------------------------ -----Page 2
|      |     F   |     | (7)
------------------------
|      |     F   |     | (8)
------------------------
|      |     G   |     | (9) -----Page 3

即搜索“F”将返回 6。

谢谢。

尝试做第一部分:How do I query a SQL database to return the first "page" containing the specified data?

找到这些:
sequential row numbers from query

sqlite Retrieve Rownumber in sqlite

【问题讨论】:

标签: sql database database-design sqlite


【解决方案1】:
SELECT COUNT(*)
FROM tbl
WHERE letter < 'F'

(你会得到减一的数字,所以你必须在之后将它加一)

【讨论】:

  • 确实如此。但请注意,NULL 值不会包含在计数中。
【解决方案2】:

试试这个,但我不考虑性能

--create table
create table t(letter char(1))
go

--insert values
BEGIN TRAN
INSERT INTO t VALUES ('A')
INSERT INTO t VALUES ('B')
INSERT INTO t VALUES ('C')
INSERT INTO t VALUES ('D')
INSERT INTO t VALUES ('E')
INSERT INTO t VALUES ('F')
INSERT INTO t VALUES ('F')
INSERT INTO t VALUES ('F')
INSERT INTO t VALUES ('G')
COMMIT TRAN
GO

--and then try the select what you want
DECLARE @temp table(num int identity(1,1), letter char(1))

--use a temp table variable to store the data with row number
insert into @temp
SELECT * FROM t

--select the value
SELECT * FROM @temp WHERE letter = 'F'
GO

--drop the table finally
drop table t
GO

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    相关资源
    最近更新 更多