在SQLITE查询中对计数求和

时间:2017-10-31 20:34:18

标签: python sqlite

在我的sqlite查询中,我试图不仅得到计数而且还计算总数。这就是我到目前为止所做的:

sql = c.execute("SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='' GROUP BY Org ORDER BY NUM DESC")
sql_list = list(sql)
list_count = len(sql_list)
print("2014 Data:")

for i in sql_list:
    print(i)

sql_sum = c.execute("SELECT SUM(NUM) FROM (SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='')")
sum_list = list(sql_sum)
print("Sum =", sum_list)
print()

我得到第一个sql查询的正确输出,但是我没有得到第二个的正确输出。

非常感谢任何帮助!

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果您希望从第一个sql语句中获取表的总和,那么您似乎错过了在第一个查询中添加的组(GROUP BY Org)。没有数据库和预期的结果,下面是我期望的将为您工作。

sql = c.execute("SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='' GROUP BY Org ORDER BY NUM DESC")
sql_list = list(sql)
list_count = len(sql_list)
print("2014 Data:")

for i in sql_list:
    print(i)

sql_sum = c.execute("SELECT SUM(NUM) FROM (SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='' GROUP BY Org )")
sum_list = list(sql_sum)
print("Sum =", sum_list)