Cooper
Cooper

Reputation: 205

Python sqlite3 - retrieve every n-1 row in database

I have a database of values with the first column being an identifying number for each row in my database.

What I want to do is create a function to retrieve every n-1 (or n-offset) row so if I give a number like '50' to the function, it will print the database that have the row numbers that are a multiple of 50-1. So inputting '50' will give the rows of '49', '99', '149', '199', etc instead of '50', '100', '150', '200' and print the database with those specific rows.

This is what I have so far:

import sqlite3
from tabulate import tabulate

def retrieve_nth_row(rownum):
    with conn:
        data = c.execute(f"SELECT * FROM Table_name WHERE IdNum > 0 and IdNum <= (SELECT max(IdNum) FROM Anime) AND IdNum % {rownum} = 0")
    print(tabulate(data, headers="keys", tablefmt="grid", stralign='center', numalign='center'))   #Prints the database as a neat table

The code I have prints out the database for every multiple of 'rownum' specified (so 'rownum' = 50 prints out rows 50,100,150,200, etc). I can't seem to figure out how to add a offset it to print out 'rownum'-(offset) rows.

Upvotes: 0

Views: 69

Answers (1)

CL.
CL.

Reputation: 180060

 49 % 50 is 49.
 99 % 50 is 49.
149 % 50 is 49. etc.

every = 50
offset = 1
c.execute("SELECT ... WHERE ... idNum % ? = ?",
          [every, (every - offset) % every])

(The extra % in the second parameter is necessary if the offset is zero.)

Upvotes: 1

Related Questions