我正在尝试在列中返回唯一值的数量,但它没有按预期工作。例如:
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')
答案 0 :(得分:4)
您正在使用:
select columnName, count(columnName) as CountOf from tableName group by columnName
这应该是:
select columnName, count(*) as CountOf from tableName group by columnName
正确聚合GROUP BY。
答案 1 :(得分:1)
非常感谢@JonClements的解决方案。
在原始帖子中alertsSQL(inputA)
由于for循环被多次调用,inputA
本身就是在每个for循环中生成的列表。在下面的代码中,正在接收的列表(即' ALL
')是嵌套列表。它还适当地修改和组织来自alertsSQL()
的内容 - 由于前面提到的for循环,该内容之前被执行了多次。
def init_db(filename=':memory:'):
db = sqlite3.connect(filename)
db.execute("CREATE TABLE Alerts (SID INT, Signature TEXT)")
return db
db = init_db()
someFunction() # Function generates a nested list i.e. ALL
db.executemany("INSERT INTO Alerts (SID, Signature) VALUES (?,?)", (ALL))
c = db.cursor()
c.execute('SELECT SID, count(*) as CountOf from Alerts group by SID')
result=c.fetchall()