python - 将一列中的值相乘

标签 python sqlite

我正在通过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/

相关文章:

python - 有没有更 Pythonic 的方法来解决这个问题?

python - 嵌套 WTForms FieldList 在字段中生成 HTML

python - selenium python 中的多线程

python - python 是否自动并行化 IO 和 CPU 或内存绑定(bind)部分?

sqlite 选择日期条件

sql - 使用 sqlite json_each 过滤 json 数组中的多个项目

sql - 在SQLite中CREATE UNIQUE INDEX或INTEGER PRIMARY KEY的性能更高吗?

database - 使用qt在数据库中的ID

IOS:从 URL 打开 sqlite

在 __init__ 中定义和设置的 Python 模拟属性