SELECT
"Code".name,
plan.value AS "plan",
fact.value AS "fact"
FROM "Code"
LEFT JOIN (
SELECT
codes,
SUM(value) AS "value"
FROM "Income_Plan"
GROUP BY codes) plan
ON plan.income_codes = "Code".id
LEFT JOIN (SELECT codes,
SUM(value) AS "value"
FROM "Income_Fact"
GROUP BY codes) fact
ON fact.codes = "Code".id
SELECT
"Code".name AS "Code_name",
sum("Income_Plan".value) AS sum_1,
sum("Income_Fact".value) AS sum_2
FROM "Code"
JOIN "Income_Plan" ON "Code".id = "Income_Plan".codes
JOIN "Income_Fact" ON "Code".id = "Income_Fact".codes
ORDER BY "Code".id;
db.session.query(
Code.name, func.sum(Income_Plan.value), func.sum(Income_Fact.value)
).select_from(Code).join(Income_Plan).join(Income_Fact).order_by(Code.id)
sq = q1.union_all(q2).subquery()
db.session.query(
func.sum(sq.c.plan), func.sum(sq.c.fact), Code.name, Code.id
).select_entity_from(sq).group_by(Code.id, Code.name)
SELECT
sum(anon_1.plan) AS sum_1,
sum(anon_1.fact) AS sum_2,
anon_1."Code_name" AS "anon_1_Code_name",
anon_1."Code_id" AS "anon_1_Code_id"
FROM (
SELECT
anon_2.plan AS plan, anon_2.fact AS fact,
anon_2."Code_id" AS "Code_id",
anon_2."Code_name" AS "Code_name"
FROM (
SELECT
"Income_Plan".value AS plan,
0 AS fact, "Code".id AS "Income_Code_id",
"Code".name AS "Code_name"
FROM "Income_Plan"
LEFT OUTER JOIN "Code" ON "Code".id = "Income_Plan".codes
UNION ALL
SELECT
0 AS plan,
"Income_Fact".value AS fact,
"Code".id AS "Code_id",
"Code".name AS "Code_name"
FROM "Income_Fact"
LEFT OUTER JOIN "Code" ON "Code".id = "Income_Fact".codes
) AS anon_2
) AS anon_1
GROUP BY anon_1."Code_id", anon_1."Code_name"
SELECT
anon_1.plan AS anon_1_plan,
anon_1.fact AS anon_1_fact,
anon_1."Income_Code_name" AS "anon_1_Income_Code_name"
FROM (
SELECT
anon_2.plan AS plan,
anon_2.fact AS fact,
anon_2."Income_Code_id" AS "Income_Code_id",
anon_2."Income_Code_name" AS "Income_Code_name"
FROM (
SELECT
"Income_Plan".value AS plan,
0 AS fact,
"Code".id AS "Income_Code_id",
"Code".name AS "Income_Code_name"
FROM "Income_Plan"
LEFT OUTER JOIN "Code" ON "Code".id = "Income_Plan".codes
UNION ALL
SELECT
0 AS plan,
"Income_Fact".value AS fact,
"Code".id AS "Income_Code_id",
"Code".name AS "Income_Code_name"
FROM "Income_Fact"
LEFT OUTER JOIN "Code" ON "Code".id = "Income_Fact".codes
) AS anon_2
) AS anon_1
GROUP BY anon_1."Income_Code_id"
SELECT
sum(%(param_1)s) AS sum_1, -- вот тут ошибка
sum(%(param_2)s) AS sum_2,
anon_1.name AS in_code
FROM (
SELECT "Income_Plan".value AS plan,
0 AS fact,
"Code".id AS id,
"Code".name AS name
FROM "Income_Plan"
LEFT OUTER JOIN "Code" ON "Code".id = "Income_Plan".Codes AS anon_2
UNION ALL
SELECT 0 AS plan,
"Income_Fact".value AS fact,
"Code".id AS id,
"Code".name AS name
FROM "Income_Fact"
LEFT OUTER JOIN "Code" ON "Code".id = "Income_Fact".Codes AS anon_3
) AS anon_1 GROUP BY anon_1.id