Python Sqlite3库忽略'HAVING'子句

时间:2014-09-09 04:35:08

标签: python sql sqlite

我正在编写一个脚本,找到与第一个百分比大于0.4相对应的级别。

例如,请考虑表格:

enter image description here

使用SQLite Manager Extension for Firefox运行

SELECT source, receiver, level FROM results WHERE percentage > 0.4 GROUP BY source,   receiver HAVING percentage = min(percentage)

产生我想要的数据:

enter image description here

但是,当我运行以下Python脚本

import sqlite3
db = sqlite3.connect("test.sqlite")

cursor = db.cursor()

sql = "SELECT * FROM results"
print "Executing", sql
cursor.execute(sql)
for row in cursor:
    print row

sql = ("SELECT source, receiver, level FROM results WHERE percentage > 0.4 "
        "GROUP BY source, receiver HAVING percentage = min(percentage)")
print "Executing", sql
cursor.execute(sql)
for row in cursor:
    print row

sql = ("SELECT * FROM ("
       "SELECT source, receiver, level "
       "FROM results WHERE percentage > 0.4 ORDER BY percentage DESC)"
       "GROUP BY source, receiver")
print "Executing", sql
cursor.execute(sql)
for row in cursor:
    print row
print "Done!"

我得到以下输出:

Executing SELECT * FROM results
(u'S1', u'R1', 10, 0.1)
(u'S1', u'R1', 11, 0.5)
(u'S1', u'R1', 12, 0.6)
(u'S2', u'R1', 10, 0.2)
(u'S2', u'R1', 11, 0.3)
(u'S2', u'R1', 12, 0.5)
(u'S2', u'R1', 13, 1)
(u'S1', u'R1', 13, 1)
Executing SELECT source, receiver, level FROM results WHERE percentage > 0.4 GROUP BY source, receiver HAVING percentage = min(percentage)
Executing SELECT * FROM (SELECT source, receiver, level FROM results WHERE percentage > 0.4     ORDER BY percentage DESC) GROUP BY source, receiver
(u'S1', u'R1', 11)
(u'S2', u'R1', 12)
Done!

可以看出,在SQLite Manager中执行的同一查询不返回任何行。

我在第三个查询中包含了一个具有预期结果的工作。

我正在使用Windows 7.1 32位,从Anaconda发行版运行Python构建:

Python 2.7.5 |Anaconda 1.8.0 (32-bit)| (default, Jul  1 2013, 12:41:55) [MSC v.1500 32 bit (Intel)] on win32

有什么可能导致这个问题的想法?

由于

1 个答案:

答案 0 :(得分:1)

当您使用GROUP BY时,每个组都会得到一个输出行。

在SELECT和HAVING子句中,您正在使用该输出行中的值。 这意味着您只能使用GROUP BY子句中的列(在组的每个源行中具有相同的值)或聚合函数的结果(如min(percentage))。 如果您使用任何其他列,则从某个随机行获取值。

在这种情况下,levelpercentage来自组中的某个随机行。 这使得percentage = min(percentage)比较在某些情况下失败。


在SQLite 3.7.11或更高版本中,在SELECT子句中使用min()max()可确保其他列的值来自与min / {{匹配的源行1}}:

max