Answer the question
In order to leave comments, you need to log in
How to combine 2 complex sqlalchemy queries?
Good afternoon.
There are 2 tables in the SQLite database. You need to take data from the "quantity" column from one table, sum it up and group it by the values in the "barcode" column. It worked out.
You need to take the data of the "quantity" column from the second table, sum it up and group it by the values in the "barcode" column. This also worked out.
Then you need to combine them by the "barcode" value.
Foreign keys are not used for tables.
Here are the models:
class Incomes(db.Model):
__tablename__ = "incomes"
number = db.Column(db.Integer, primary_key=True, autoincrement=True)
barcode = db.Column(db.String(30))
quantity = db.Column(db.Integer)
def __init__(self, barcode, quantity):
self.barcode = barcode
self.quantity = quantity
class Sales(db.Model):
__tablename__ = "sales"
barcode = db.Column(db.String(30))
quantity = db.Column(db.Integer)
saleID = db.Column(db.String(30), primary_key=True)
def __init__(self, barcode, quantity, saleID):
self.barcode = barcode
self.quantity = quantity
self.saleID = saleID
incomesQuery = db.session.query(models.Incomes, func.sum(models.Incomes.quantity).label('inc')).group_by(models.Incomes.barcode).all()
salesQuery = db.session.query(models.Sales, func.sum(models.Sales.quantity).label('sal')).group_by(models.Sales.barcode).all()
Answer the question
In order to leave comments, you need to log in
Here is a possible solution:
select barcode, sum(if (tbl='incomes',quantity,0)) as inc_quant, sum(if (tbl='sales',quantity,0)) as sal_quant
from
(
select 'b' as barcode, 5 as quantity, 'incomes' as tbl
union all
select 'c' as barcode, 7 as quantity, 'incomes' as tbl
union all
select 'b' as barcode, 10 as quantity, 'sales' as tbl
union all
select 'c' as barcode, 100 as quantity, 'sales' as tbl
) subquery
group by barcode
;
"barcode" "inc_quant" "sal_quant"
"b" "5" "10"
"c" "7" "100"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question