sqlite3未按计数分组

sqlite3未按计数分组

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

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']


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

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/

10-13 00:07