Например, один из моих выходных данных выглядит так:
Код: Выделить всё
INSERT INTO my_table (a, b, c) SELECT my_table2.d, bar.e, bar.f
FROM my_table2 JOIN (SELECT my_table3.e AS e, max(my_table3.f) AS f, count(my_table3.g) AS g
FROM my_table3
WHERE my_table3.h = 'foo' GROUP BY my_table3.e
HAVING count(my_table3.g) = 1) bar ON my_table2.g = bar.g
Код: Выделить всё
INSERT INTO my _table (a, b c)
SELECT my_table2.d, bar.e, bar.f
FROM my_table2 JOIN (
SELECT my_table3.e, max(my_table3.f), count(my_table3.g)
FROM my_table3
WHERE my_table3.h = 'foo'
GROUP BY my_table3.e
HAVING count(my_table3.g) = 1
) bar ON my_table2.g = bar.g
Для репликации:
из импорта sqlalchemy table, columns, String, Numeric, func, select
из sqlalchemy.dialects import oracle
my_table = table('my_table', columns('a ', String), columns('b', String), columns('c', String))
my_table2 = table('my_table2', columns('d', String), columns('g', String))
my_table3 = table('my_table3', columns('d', String), columns('e', String), columns('f', Numeric), columns('g', String) , columns('h', String))
inner_sel = select([my_table3.c.e, func.max(my_table3.c.f).label('f'), func.count(my_table3.c.g ).label('g')]).where(my_table3.c.h=='foo').group_by(my_table3.c.e).having(func.count(my_table3.c.g)==1).alias('bar' )
outer_sel = select([my_table2.c.d, Inner_sel.c.e, Inner_sel.c.f]).select_from(my_table2.join(inner_sel, my_table2.c.g==inner_sel.c.g))
ins = my_table.insert().from_select([my_table.c.a, my_table.c.b, my_table.c.c], external_sel)
print ins.compile(dialect=oracle .dialect(), compile_kwargs={'literal_binds': True})
Подробнее здесь: https://stackoverflow.com/questions/443 ... sqlalchemy