python - sqlite3 不按计数分组

标签 python sqlite

我试图返回列中唯一值的数量,但它没有按预期工作。例如:

select columnName, count(columnName) as CountOf from tableName group by columnName
result = c.fetchone()
print result

....将返回:

(627, 1)
(399, 1)
(1714, 1)
(1714, 1)
(88, 1)
(88, 1)

我也试过:

SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name
result = c.fetchone()
print result

...返回:

(1,)
(1,)
(1,)
(1,)
(1,)
(1,)

期望的输出(关于第一条语句)类似于:

(627, 1)
(399, 1)
(1714, 2)
(88, 2)

我使用的代码是:

def alertsSQL(inputA):

    conn = sqlite3.connect(':memory:')
    c = conn.cursor()
    allT = "SELECT * FROM Alerts"

    c.execute("CREATE TABLE Alerts (SID INT, Signature TEXT)")
    c.execute("INSERT INTO Alerts (SID, Signature) VALUES (?,?)", (inputA))
    conn.commit()

    c.execute('SELECT SID, count(*) as CountOf from Alerts group by SID')
    result=c.fetchall()

    print result

输入“inputA”的列表具有以下性质:

[1714, 'NETBIOS SMB-DS Session Setup']

注意在上面的代码中,为了清楚起见,我只是减少了列数。数据已正确插入,我通过以下方式验证:

for row in c.execute(allT):
        print row

生成表中的每一行,例如一排是:

(1714, u'NETBIOS SMB-DS Session Setup')

最佳答案

您正在使用:

select columnName, count(columnName) as CountOf from tableName group by columnName

这应该是:

select columnName, count(*) as CountOf from tableName group by columnName 

为了正确聚合 GROUP BY。

关于python - sqlite3 不按计数分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25309708/

相关文章:

python - 如何自动从工程图图像中裁剪图?

python - Python,Eclipse中正则表达式字符串的pep8警告

Python File IO - 构建字典并查找最大值

android - 从数据库中获取特定行时抛出数字格式异常

python sqlite插入命名参数或null

c# - 使用 Microsoft.EntityFrameworkCore.Sqlite 从 SQLite 数据库进行逆向工程

python - 使用python创建小型docker grpc服务

.net - 使用 ODBC 和 C++ Net 将空 BLOB 插入 SQLite DB

ios - Sqlite3 查询在 iOS 8.2 下变得非常慢

python - BeautifulSoup- find_all- 订单保存