繁体   English   中英

python sqlite3对每种类型求和

[英]python sqlite3 sum each type

我有一个表(foos),它是Foos的列表,每种Foo类型都有一行。 第二个表(项目)是一个列表,其中每一行都是Foo的类型和数量(和其他信息)。 例如,Foo3,45.2和Foo2,12.34。

我想确定每种Foo的总金额。

这是我现有的代码,但是必须有一种更好的(更标准或更有效的)方法:

cursor.execute('''select type from foos''')
foo_types = cursor.fetchall()
results = []
for ft in foo_types:
    cursor.execute('''select sum(amount) from items
        where foo_type =?''', ft)
    results.append((ft, cursor.fetchone()))

我应该如何编码?

SELECT foo_type, SUM(amount)
FROM items
GROUP BY foo_type

在一个查询中已经为您提供了每个foo_type和相应的sum 您可以从中构建字典,并使用它来扩展第一个查询的数据。

或者将所有内容放入一个查询中:

cursor.execute("SELECT foo_type, SUM(amount) "
               "FROM items, foos "
               "WHERE items.foo_type = foos.type "
               "GROUP BY foo_type")
results = list(cursor)

# results is a list of tuples: [(type1, sum1), (type2, sum2), ...]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM