Introduction to Databases in Python
Jason Myers
Co-Author of Essential SQLAlchemy and Software Engineer
managers = employees.alias()
stmt = select( [managers.columns.name.label('manager'), employees.columns.name.label('employee')])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.order_by(managers.columns.name)
print(connection.execute(stmt).fetchall())
[(u'FILLMORE', u'GRANT'),
(u'FILLMORE', u'ADAMS'),
(u'HARDING', u'TAFT'), ...
group_by()
at the right aliasmanagers = employees.alias()
stmt = select([managers.columns.name, func.sum(employees.columns.sal)])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.group_by(managers.columns.name) print(connection.execute(stmt).fetchall())
[(u'FILLMORE', Decimal('96000.00')),
(u'GARFIELD', Decimal('83500.00')),
(u'HARDING', Decimal('52000.00')),
(u'JACKSON', Decimal('197000.00'))]
Introduction to Databases in Python