我正在通过python 2.7使用sqlite3。
我有一个表,我想在其中B列相同的C列中乘以值。
如果这些值在不同的列中,它将更加简单
我可以用SELECT B, C1 *C2 FROM table1;
但是当涉及到在一列中乘法时,我迷失了。
例如,如果这是原始表
A B C
1 Mike 2.5
1 Susan 4.2
1 Patti 2.0
2 Susan 1.1
2 Patti 3.7
3 Mike 0.2
然后在B列中的条目相同的情况下,将C列中的它们的值相乘,因此我的输出为
A B
Mike 0.5
Susan 4.62
Patti 7.4
最佳答案
正如评论中指出的那样,很难为SQLite中的乘法创建聚合函数。但是,可以通过使用itertools.groupby
执行组合和乘法操作,然后创建一个新表来解决此问题。此答案利用上下文管理器和属性装饰器创建一个干净的类调用:
import sqlite3
import itertools
class UpdateTable:
def __init__(self, *args):
self.__dict__ = dict(zip(['table', 'filename'], args))
self.new_table = None
@property
def newtable(self):
return self.new_table
@newtable.setter
def newtable(self, new_table_name):
self.new_table = new_table_name
def __enter__(self):
data = map(lambda (a, b, c):[b, float(c)], list(sqlite3.connect(self.filename).cursor().execute('SELECT * FROM {}'.format(self.table))))
self.new_data = [(a, reduce(lambda x, y:x[-1]*y[-1], list(b))) for a, b in itertools.groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])]
return self
def __exit__(self):
conn = sqlite3.connect(self.filename)
conn.execute('CREATE TABLE {} (A text, B float)'.format(self.new_table))
conn.executemany('INSERT INTO {} VALUES (?, ?)'.format(self.new_table), self.new_data)
conn.commit()
conn.close()
with UpdateTable('table', 'db_file.db') as t:
t.newtable = 'table2'
Python3需要
functools
用于reduce
,并且与lambda元组拆包不兼容。Python3版本:
import functools
import sqlite3
import itertools
class UpdateTable:
def __init__(self, *args):
self.__dict__ = dict(zip(['table', 'filename'], args))
self.new_table = None
@property
def newtable(self):
return self.new_table
@newtable.setter
def newtable(self, new_table_name):
self.new_table = new_table_name
def __enter__(self):
data = map(lambda x:[x[1], float(x[-1])], list(sqlite3.connect(self.filename).cursor().execute('SELECT * FROM {}'.format(self.table))))
self.new_data = [(a, functools.reduce(lambda x, y:x[-1]*y[-1], list(b))) for a, b in itertools.groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])]
return self
def __exit__(self):
conn = sqlite3.connect(self.filename)
conn.execute('CREATE TABLE {} (A text, B float)'.format(self.new_table))
conn.executemany('INSERT INTO {} VALUES (?, ?)'.format(self.new_table), self.new_data)
conn.commit()
conn.close()
with UpdateTable('table', 'db_file.db') as t:
t.newtable = 'table2'
关于python - 将一列中的值相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48216505/