1
我想在使用Python(我正在使用sqlite3)的SQL查詢中執行算術運算。 我的SQL表(TwTbl)有一個coloumn geo_count(數字)。我必須計算Geo_count Coloumn的數字大於0的條目數,並計算Geo_count = 0的條目數,然後減去它們。即使用Python在SQL查詢(嵌套Select語句)中的算術運算
(number of entries with Geo_count = 0) - (number of entries with Geo_count > 0)
我必須爲此編寫一個嵌套的select語句。
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()
這是給我一個語法錯誤
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: near "SELECT": syntax error
我試着寫以另一種方式此查詢。它不給我任何語法錯誤,但不是預期的結果。如果我運行下面的查詢,我得到0
c.execute("select count(geo_count) from TwTbl where geo_count == 0 -
(select count(geo_count) from TwTbl where geo_count <> 0)").fetchall()
雖然如果我運行單獨的查詢結果如下:
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
我不知道正確的語法。不知道我在做什麼錯。
它的工作效果很好。非常感謝。 –