我有一个查询
allcategory = db.session.query(func.count(marketItem.subcategory).label("help"),Subcategories.subname1)
allcategory = allcategory.join(Subcategories)
allcategory = allcategory.filter(marketItem.subcategory == Subcategories.id)
allcategory = allcategory.filter(marketItem.vendor_id==vendorprofile.id)
allcategory = allcategory.group_by(marketItem.id)
for allcat in allcategory.all():
print(allcat)
那将结果输出为
(1, 'Consoles')
(1, 'Consoles')
(1, 'Paintings')
(1, 'Paintings')
(1, 'Paintings')
我希望他们成为
(2, 'Consoles')
(3, 'Paintings')
如果它也可以用常规的sql术语来解释,那也会有所帮助。
答案 0 :(得分:2)
您应按Subcategory.subname1
分组:
allcategory = db.session.query(func.count(marketItem.subcategory).label("help"),
Subcategories.subname1)
allcategory = allcategory.join(Subcategories)
allcategory = allcategory.filter(marketItem.subcategory==Subcategories.id)
allcategory = allcategory.filter(marketItem.vendor_id==vendorprofile.id)
allcategory = allcategory.group_by(Sucategories.subname1) # < change here
for allcat in allcategory.all():
print(allcat)
在SQL中,您必须按照未汇总的字段进行分组 - 在本例中为Subcategories.subname1
。