1

I am trying to do an arithmetic operation in a SQL query using Python (I am using sqlite3). My SQL Table (TwTbl) has a coloumn geo_count(number). I have to count the number of entries in which the Geo_count Coloumn has a number greater than 0, and also count the number of entries with Geo_count = 0 and then subtract them. i.e.

(number of entries with Geo_count = 0) - (number of entries with Geo_count > 0)

I have to write a nested select statement for that.

import sqlite3
c.execute("SELECT (COUNT(SELECT geo_count FROM TwTbl WHERE geo_id == 0) – 
          COUNT(SELECT geo_count FROM TwTbl WHERE geo_count IS <> 0)) FROM TwTbl").fetchall()

This is giving me a syntax error

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
sqlite3.OperationalError: near "SELECT": syntax error

I tried writing this query in another way. It is not giving me any syntax error, but not the expected results. If I run the following query I get 0.

c.execute("select count(geo_count) from TwTbl where geo_count == 0 - 
         (select count(geo_count) from TwTbl where geo_count <> 0)").fetchall()

Although If I run the queries individually the results are as follows:

c.execute("select count(geo_count) from TwTbl where geo_count <> 0").fetchall()
>>> 13
c.execute("select count(geo_count) from TwTbl where geo_count ==0").fetchall()
>>> 880

I am not sure about the correct syntax. Not sure what am I doing wrong.

1 Answer 1

1
SELECT SUM(geo_count==0) - SUM(geo_count<>0) FROM TwTbl
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.