我在Peewee中有两个查询,第一个查询返回一个与最小值和最大值匹配的捐赠表,然后乘以一个因子。另一笔将退回所有超出最小/最大范围的捐款。它们运行之后,我使用UNION ALL运算符获得了一组组合的结果:
database.execute_sql('PRAGMA foreign_keys = ON;')
with database.transaction():
# part multiplied by factor
query1 = (Donation
.select(Donation.donor.alias('donor'),
fn.SUM((Donation.amount)*factor).alias('total'))
.where(
(Donation.amount > min_donation) &
(Donation.amount < max_donation)
)
.group_by(Donation.donor)
)
query2 = (Donation
.select(Donation.donor.alias('donor'),
(fn.SUM(Donation.amount)).alias('total'))
.where(
#(Donation.amount <= min_donation) &
(Donation.amount >= max_donation)
)
.group_by(Donation.donor)
)
query = ((query1 + query2)
.select(
SQL('donor'),
fn.SUM(SQL('total'))
)
.group_by(SQL('donor'))
.order_by(SQL('donor'))
)
它现在的编码方式,它抱怨我无法在组合查询中选择:
Traceback (most recent call last):
File "run_mailroom_db.py", line 350, in project
for i in query:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/peewee.py", line 1611, in __iter__
self._ensure_execution()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/peewee.py", line 1607, in _ensure_execution
raise ValueError('Query has not been executed.')
现在,我的问题是,是否有一种方法可以从组合查询中提取单个列,并像返回数据库表一样执行返回分组值的SUM之类的事情?
答案 0 :(得分:0)
在实现了此处提出的解决方案之后,这是更新的代码:
database.execute_sql('PRAGMA foreign_keys = ON;')
with database.transaction():
# part multiplied by factor
query1 = (Donation
.select(Donation.donor.alias('donor'),
fn.SUM((Donation.amount)*factor).alias('total'))
.where(
(Donation.amount > min_donation) &
(Donation.amount < max_donation)
)
.group_by(Donation.donor)
)
query2 = (Donation
.select(Donation.donor.alias('donor'),
(fn.SUM(Donation.amount)).alias('total'))
.where(
(Donation.amount <= min_donation) |
(Donation.amount >= max_donation)
)
.group_by(Donation.donor)
)
query = ((query1 + query2)
.select(
SQL('donor'),
fn.SUM(SQL('total'))
)
.group_by(SQL('donor'))
.order_by(SQL('donor'))
)
pp.pprint("="*60)
pp.pprint("Projected Donors for factor: {}, min: {}, max: {}".format(factor,
min_donation,
max_donation)
)
pp.pprint('{:30} | {:30}'.format(
'Donor',
'Total'))
pp.pprint("="*60)
for i in query.execute(database):
pp.pprint("{:30} | {:30}".format(str(i['donor']),
str(i['SUM(total)'])
)
)