Python sqlite3 按类型求和

0 投票
1 回答
3389 浏览
提问于 2025-04-17 06:30

我有一个表格(foos),里面列出了各种类型的Foo,每种Foo占一行。还有一个第二个表格(items),每一行记录了某种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()))

我该怎么写代码呢?

1 个回答

4
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), ...]

撰写回答