在查询中计算值

Python 中的数据库入门

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

数学运算符

  • 加法 +
  • 减法 -
  • 乘法 *
  • 除法 /
  • 取模 %
  • 不同数据类型的行为不同
Python 中的数据库入门

计算差值

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)]
Python 中的数据库入门

Case 语句

  • 根据条件对数据作不同处理
  • 接收条件列表;匹配时返回对应列
  • 条件列表以 else 子句结束,用于未匹配记录
Python 中的数据库入门

Case 示例

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,)]
Python 中的数据库入门

Cast 语句

  • 将数据转换为另一种类型
  • 适用于转换:
    • 整数为浮点数以便除法
    • 字符串为日期/时间
  • 接收一个列或表达式及目标 Type
Python 中的数据库入门

百分比示例

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'),)]
Python 中的数据库入门

开始练习吧!

Python 中的数据库入门

Preparing Video For Download...