【问题标题】:Arithmetic Operation in a SQL query (nested Select statement) using Python使用 Python 的 SQL 查询(嵌套的 Select 语句)中的算术运算
【发布时间】:2013-11-21 09:02:26
【问题描述】:

我正在尝试使用 Python 在 SQL 查询中进行算术运算(我使用的是 sqlite3)。 我的 SQL 表 (TwTbl) 有一个列 geo_count(number)。我必须计算 Geo_count 列的数字大于 0 的条目数,还要计算 Geo_count = 0 的条目数,然后减去它们。即

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

我必须为此编写一个嵌套的选择语句。

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

我不确定正确的语法。不知道我做错了什么。

【问题讨论】:

    标签: python sql sqlite


    【解决方案1】:
    SELECT SUM(geo_count==0) - SUM(geo_count<>0) FROM TwTbl
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 2023-03-10
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      相关资源
      最近更新 更多