【问题标题】:python - Fetching rows in between a range of rownumbers with python and pymssqlpython - 使用 python 和 pymssql 获取一系列行号之间的行
【发布时间】:2017-10-20 19:21:21
【问题描述】:

我想使用 python 包 pymssql 从数据库中获取特定范围的行号。我正在使用以下似乎不起作用的代码

# connection details to SQL
con = pymssql.connect("some connection credentials")

df = pd.read_sql("""SELECT
            [col1], 
            [col2],
            WHERE rownum 
            BETWEEN 0 AND 1000""", 
            con = con)

它显示以下错误:

(207, "Invalid column name 'rownum'.DB-Lib error message 20018, severity
16:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib
error message 20018, severity 16:\nGeneral SQL Server error: Check 
messages from the SQL Server\n")

我做错了什么?这不是连接问题,如果我选择前 1000 行,它可以完美运行。

【问题讨论】:

    标签: python sql pymssql


    【解决方案1】:

    您似乎想使用ROW_NUMBER() 窗口函数,您可以使用类似于以下的查询来完成:

    sql = """\
    SELECT [id], [txtcol] 
    FROM 
        (
            SELECT [id], [txtcol], ROW_NUMBER() OVER (ORDER BY id) AS [rownum]
            FROM test10k
        ) AS subquery
    WHERE [rownum] BETWEEN 2 AND 4
    """
    crsr.execute(sql)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 2022-01-17
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多