Waarden berekenen in een query

Introductie tot databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Rekenoperatoren

  • optelling +
  • aftrekking -
  • vermenigvuldiging *
  • deling /
  • modulus %
  • Werken anders per datatype
Introductie tot databases in Python

Verschil berekenen

stmt = select([census.columns.age,           
        (census.columns.pop2008 -
        census.columns.pop2000).label('pop_change')
    ])

stmt = stmt.group_by(census.columns.age) stmt = stmt.order_by(desc('pop_change'))
stmt = stmt.limit(5)
results = connection.execute(stmt).fetchall() print(results)
[(61, 52672), (85, 51901), (54, 50808), (58, 45575),
(60, 44915)]
Introductie tot databases in Python

Case-statement

  • Gebruik om data anders te behandelen op basis van een voorwaarde
  • Accepteert een lijst met voorwaarden en een kolom om te retourneren als de voorwaarde klopt
  • Eindigt met een else-clausule voor records die geen enkele voorwaarde matchen
Introductie tot databases in Python

Case-voorbeeld

from sqlalchemy import case

stmt = select([ func.sum( case([ (census.columns.state == 'New York', census.columns.pop2008) ], else_=0))])
results = connection.execute(stmt).fetchall() print(results)
[(19465159,)]
Introductie tot databases in Python

Cast-statement

  • Zet data om naar een ander type
  • Handig om te converteren...
    • integers naar floats voor deling
    • strings naar datums en tijden
  • Accepteert een kolom of expressie en het doeldatatype
Introductie tot databases in Python

Percentagevoorbeeld

from sqlalchemy import case, cast, Float

stmt = select([ (func.sum( case([ (census.columns.state == 'New York', census.columns.pop2008) ], else_=0)) / cast(func.sum(census.columns.pop2008), Float) * 100).label('ny_percent')])
results = connection.execute(stmt).fetchall() print(results)
[(Decimal('6.4267619765'),)]
Introductie tot databases in Python

Laten we oefenen!

Introductie tot databases in Python

Preparing Video For Download...