1.6 获得一列数据的平均值(get average value of a column)
# sql language: select avg(txPkt) from Flow
from sqlalchemy.sql import func
q = session.query(func.avg(Flow.txPkt)).filter(Flow.trace_id == 1)
print q[0][0]
# The type of q is sqlalchemy.orm.query.Query
# The type of q[0] is sqlalchemy.util._collections.KeyedTuple
# The type of q[0][0] is decimal.Decimal
1.7 多列数据平均值的计算(compute average values of columns)
q = session.query((func.avg(Flow.txPkt)+func.avg(Flow.rxPkt))/2).filter(Flow.trace_id == 1)
1.8 对查询到的数据排序(order by )
from sqlalchemy import desc
q = session.query(Flow.timestamp).filter(trace_id == 1).order_by(desc(Flow.timestamp))
1.9 分组查询
q = session.query(Flow.dstIP, Flow.dstPort, func.count(Flow.id)).filter(Flow.trace_id == tid).group_by(Flow.dstIP, Flow.dstPort).all()
2 查询中,常用的过滤操作
等于(equals), 例如 query.filter(name == ‘Jack‘)
不等于(not equals), 例如 query.filter(name != ‘Jack‘)
在列表中(in), 例如 query.filter(name.in_([‘Micheal‘, ‘Bob‘, ‘Jack‘]))
不在列表中(not in), 例如query.filter(~name.in_([‘Micheal‘, ‘Bob‘, ‘Jack‘]))
空值(null), 例如 query.filter(name == None)
不是空值(not null), 例如 query.filter(name != None)
与(and), 例如 query.filter(and_(name == ‘Andy‘, fullname == ‘Andy Liu‘ ))
and_可以省略, 例如 query.filter(name==‘Andy‘, fullname==‘Andy Liu‘)
或(or), 例如 query.filter(or_(name == ‘Andy‘, name == ‘Micheal‘))