Question

i'm having trouble doing a CASE statement in order to sum how many events of a variable happens to be = 1 inside a specific range in a sqlite table. i'm a new user of sql and sqlite so i dont know how to fix it. i'd appreciate if anyone can give me a little help.

winpct.execute("SELECT SuM(CASE WHEN PLACE=1 THEN 1 ELSE 0 END, from BASEINICIAL WHERE ID < 2 AND ID > 0 AND name = 'name')")

so i have the table BASEINICIAL and i want to know how many variable "PLACE" are equal = 1. And i need to select a range based on the "id" and "name" variables.

Was it helpful?

Solution

You should move your case expression condition to the where clause :

select count(PLACE) 
from BASEINICIAL 
where ID < 2
  and ID > 0
  and name = 'name'
  and PLACE = 1

OTHER TIPS

Your problem is not with Python, but rather with SQL for SQlite.

I would recommend you to:

  • write your SQL statement nicely formatted - this often reveals problems immediately
  • consult SQLite documentation for given type of query you are going to do
  • test corrected query on sqlite3 console or any other sqlite client you have
  • finally, call it from Python

Here is reformatted SQL you have provided:

SELECT SUM(
  CASE
    WHEN PLACE=1
      THEN 1
    ELSE 0
  END,
  from BASEINICIAL
  WHERE ID < 2 AND ID > 0 AND name = 'name')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top