• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python func.sum函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sqlalchemy.sql.func.sum函数的典型用法代码示例。如果您正苦于以下问题:Python sum函数的具体用法?Python sum怎么用?Python sum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sum函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: calc_level_type_skill

 def calc_level_type_skill(self, until=None):
     query1 = (
         db.session.query(func.count(TriggeredEvent.id), func.sum(TriggeredEvent.given_skill_points).label("sum_1"))
         .join(Participation)
         .join(LevelInstance)
         .join(Level)
         .join(Level.level_types)
         .filter(Participation.pid == self.pid)
         .filter(LevelType.id == self.ltid)
     )
     query2 = (
         db.session.query(func.sum(TriggeredEvent.given_score_points).label("sum_1"))
         .join(Participation)
         .join(LevelInstance)
         .join(Level)
         .join(Level.level_types)
         .filter(Participation.pid == self.pid)
         .filter(LevelType.id == self.ltid)
         .group_by(LevelInstance.id)
         .order_by(desc("sum_1"))
     )
     if until:
         query1 = query1.filter(TriggeredEvent.timestamp < until)
         query2 = query2.filter(TriggeredEvent.timestamp < until)
     considered_rows, skill_points = query1.all()[0] if query1.all()[0] else 0
     score_points = query2.all()[0][0] if query2.all() else 0
     return considered_rows, skill_points, score_points
开发者ID:lexxodus,项目名称:gacfacg,代码行数:27,代码来源:models.py


示例2: get_line_sum

def get_line_sum():
	line = int(request.form['line'])
	chosen_direction = request.form['direction']
	if chosen_direction in ['Inbound','Outbound']:
		for result in db.session.query(func.count(Output.ZONE_NUMBER.distinct())).filter_by(LINE_NUMBER = line, DIRECTION = chosen_direction):
			length = result[0]
			zones, fare, cost = initialize_variables(length)
		i = 0
		while (i < length):
			zones[i] =  db.session.query(Output.ZONE_NUMBER.distinct()).filter_by(LINE_NUMBER = line, DIRECTION = chosen_direction)[i][0]
			for fare_sum in db.session.query(func.sum(Output.FARE_COLLECTED)).filter_by(LINE_NUMBER = line, ZONE_NUMBER = zones[i], DIRECTION = chosen_direction):
				fare[i] = fare_sum[0]
			for cost_sum in db.session.query(func.sum(Output.TOTAL_OPERATING_COST)).filter_by(LINE_NUMBER = line, ZONE_NUMBER = zones[i], DIRECTION = chosen_direction):
				cost[i] = cost_sum[0]
			i += 1
		return zones, fare, cost
	else:
		for result in db.session.query(func.count(Output.ZONE_NUMBER.distinct())).filter_by(LINE_NUMBER = line):
			length = result[0]
			zones, fare, cost = initialize_variables(length)
		i = 0
		while (i < length):
			zones[i] =  db.session.query(Output.ZONE_NUMBER.distinct()).filter_by(LINE_NUMBER = line)[i][0]
			for fare_sum in db.session.query(func.sum(Output.FARE_COLLECTED)).filter_by(LINE_NUMBER = line, ZONE_NUMBER = zones[i]):
				fare[i] = fare_sum[0]
			for cost_sum in db.session.query(func.sum(Output.TOTAL_OPERATING_COST)).filter_by(LINE_NUMBER = line, ZONE_NUMBER = zones[i]):
				cost[i] = cost_sum[0]
			i += 1
		return zones, fare, cost
开发者ID:areis23,项目名称:farebox6,代码行数:29,代码来源:database2.py


示例3: get_biggest_donations

    def get_biggest_donations(cls, limit=None, offset=None):
        """Getter for biggest donations.

        Donations from the same person are grouped.

        Args:
            limit: Maximum number of donations to be returned.
            offset: Offset of the result.

        Returns:
            Tuple with two items. First is total number if donations. Second
            is a list of donations sorted by amount with a specified offset.
        """
        query = db.session.query(
            cls.first_name.label("first_name"),
            cls.last_name.label("last_name"),
            cls.editor_name.label("editor_name"),
            func.max(cls.payment_date).label("payment_date"),
            func.sum(cls.amount).label("amount"),
            func.sum(cls.fee).label("fee"),
        )
        query = query.filter(cls.anonymous == False)
        query = query.group_by(cls.first_name, cls.last_name, cls.editor_name)
        query = query.order_by(desc("amount"))
        count = query.count()  # Total count should be calculated before limits
        if limit is not None:
            query = query.limit(limit)
        if offset is not None:
            query = query.offset(offset)
        return count, query.all()
开发者ID:caroline-gschwend,项目名称:metabrainz.org,代码行数:30,代码来源:donation.py


示例4: agg_supply

def agg_supply(timeid):
    s_dict = {k: 0 for k in range(1, 14)}

    ##pull units devoted to production...   
    if timeid == 1 or session.query(Inventory.id).filter(Inventory.timeid==timeid-1).count() == 0:
        result = session.query(Business.industryid, func.sum(Business.produnits)).group_by(Business.industryid).order_by(Business.industryid).all()

        for id, produnits in result:
            s = produnits * 500 
            s_dict[id] = s

            ##commit supply to the database        
            supply = Supply(timeid=timeid, industryid=id, endunits=s)
            session.add(supply)
            session.commit() 
    else:
        result = session.query(Business.industryid, func.sum(Business.produnits), func.sum(Inventory.units)).filter(Inventory.timeid==timeid-1, Business.id==Inventory.businessid).group_by(Business.industryid).order_by(Business.industryid).all()

        for id, produnits, inventory in result:    
        ##calculate the supply for each record...
            s = inventory + produnits * 500 
            s_dict[id] = s
            
            ##commit supply to the database        
            supply = Supply(timeid=timeid, industryid=id, endunits=s)
            session.add(supply)
            session.commit() 
    
    ##return a supply dataframe for program    
    df = pd.DataFrame(s_dict.values(), index=s_dict.keys(), columns=["supply"])
    return df
开发者ID:carlsonjosh,项目名称:bizsim,代码行数:31,代码来源:test_code.py


示例5: get_taxi_data_count

def get_taxi_data_count(color):
    if color == 'all':
        base_query = session.query(func.sum(TripStats.total_record_cnt))
        yellow_count = base_query.filter(TripStats.taxi_type == 2).first()[0]
        green_count = base_query.filter(TripStats.taxi_type == 1).first()[0]

        return return_json({
            "yellow": {
                "day": int(yellow_count/365),
                "week": int(yellow_count/52),
                "month": int(yellow_count/12),
                "year": int(yellow_count)
            },
            "green": {
                "day": int(green_count/365),
                "week": int(green_count/52),
                "month": int(green_count/12),
                "year": int(green_count)
            }
        })
    taxi_type = COLOR_CODE[color]
    count = session.query(func.sum(TripStats.total_record_cnt)).filter(TripStats.taxi_type == taxi_type).first()[0]
    if 'average' in request.args:
        if request.args['average'] == 'day':
            return return_json({"count": int(count/365), "type": color})
        elif request.args['average'] == 'month':
            return return_json({"count": int(count/12), "type": color})
        elif request.args['average'] == 'week':
            return return_json({"count": int(count/52), "type": color})
    return return_json({"count": count, "type": color})
开发者ID:benjamin21st,项目名称:bigdata_2016,代码行数:30,代码来源:views.py


示例6: process

    def process(self, *args, **kwargs):
        self.logtimes()
        with make_db(self.db) as db:
            try:
                nodes = db.query(models.TrNode)
                for node in nodes:
                    r = db.query(
                        func.sum(models.TrOnline.input_total).label("input_total"),
                        func.sum(models.TrOnline.output_total).label("output_total")
                    ).filter(
                        models.TrOnline.account_number == models.TrAccount.account_number,
                        models.TrAccount.customer_id == models.TrCustomer.customer_id,
                        models.TrCustomer.node_id == node.id
                    ).first()
                    if r and all([r.input_total,r.output_total]):
                        stat = models.TrFlowStat()
                        stat.node_id = node.id
                        stat.stat_time = int(time.time())
                        stat.input_total = r.input_total
                        stat.output_total = r.output_total
                        db.add(stat)

                # clean expire data
                _time = int(time.time()) - (86400 * 2)
                db.query(models.TrFlowStat).filter(models.TrFlowStat.stat_time < _time).delete()

                db.commit()
                logger.info("flow stat task done")
            except Exception as err:
                db.rollback()
                logger.error('flow_stat_job err,%s'%(str(err)))
        
        return self.get_notify_interval()
开发者ID:myapple,项目名称:ToughRADIUS,代码行数:33,代码来源:flow_stat.py


示例7: _investments

    def _investments(self):
        today_investments = Investment.query.filter(
            cast(Investment.added_at, Date) == date.today(),
            Investment.status.in_(
                (get_enum('INVESTMENT_PENDING'),
                 get_enum('INVESTMENT_SUCCESSED'))
            )
        ).order_by("added_at desc").limit(10)

        history_investments = db_session.query(
            func.date_trunc('day', Investment.added_at),
            func.sum(Investment.amount)).group_by(
            func.date_trunc('day', Investment.added_at)
        ).order_by(func.date_trunc('day', Investment.added_at)).all()

        total_investments = db_session.query(
            func.sum(Investment.amount)).scalar()

        today_invest_amount = db_session.query(
            func.sum(Investment.amount)).filter(
            cast(Investment.added_at, Date) == date.today(),
            Investment.status.in_(
                (get_enum('INVESTMENT_PENDING'),
                 get_enum('INVESTMENT_SUCCESSED'))
            )
        ).scalar()
        if not today_invest_amount:
            today_invest_amount = 0

        app.jinja_env.globals['today_invest_amount'] = today_invest_amount
        app.jinja_env.globals['today_investments'] = today_investments
        app.jinja_env.globals['total_investments'] = total_investments
        app.jinja_env.globals['history_investments'] = history_investments
开发者ID:xxguo,项目名称:leopard,代码行数:33,代码来源:__init__.py


示例8: get_scan_information

def get_scan_information():
    if not ValidateClass.check_login():
        return redirect(ADMIN_URL + '/index')

    if request.method == "POST":
        start_time_stamp = request.form.get("start_time_stamp")[0:10]
        end_time_stamp = request.form.get("end_time_stamp")[0:10]
        start_time_array = datetime.datetime.fromtimestamp(int(start_time_stamp))
        end_time_array = datetime.datetime.fromtimestamp(int(end_time_stamp))

        if start_time_stamp >= end_time_stamp:
            return jsonify(tag="danger", msg="wrong date select.", code=1002)

        task_count = CobraTaskInfo.query.filter(
            and_(CobraTaskInfo.time_start >= start_time_stamp, CobraTaskInfo.time_start <= end_time_stamp)
        ).count()
        vulns_count = CobraResults.query.filter(
            and_(CobraResults.created_at >= start_time_array, CobraResults.created_at <= end_time_array)
        ).count()
        projects_count = CobraProjects.query.filter(
            and_(CobraProjects.last_scan >= start_time_array, CobraProjects.last_scan <= end_time_array)
        ).count()
        files_count = db.session.query(func.sum(CobraTaskInfo.file_count).label('files')).filter(
            and_(CobraTaskInfo.time_start >= start_time_stamp, CobraTaskInfo.time_start <= end_time_stamp)
        ).first()[0]
        code_number = db.session.query(func.sum(CobraTaskInfo.code_number).label('codes')).filter(
            and_(CobraTaskInfo.time_start >= start_time_stamp, CobraTaskInfo.time_start <= end_time_stamp)
        ).first()[0]

        return jsonify(code=1001, task_count=task_count, vulns_count=vulns_count, projects_count=projects_count,
                       files_count=int(files_count), code_number=int(code_number))
开发者ID:0x24bin,项目名称:cobra,代码行数:31,代码来源:DashboardController.py


示例9: project_outline

def project_outline(name):
    # name=request.args.get('name')
    P=models.Projects.query.all()
    project=models.Projects.query.filter_by(id=name).first() 
    G=project.goals.all()
    gform=goal_form(request.values)
    delete_form=DeleteRow_form()
    q_sum = (db.session.query(
    Projects.id.label("project_id"),
    Goals.id.label("goal_id"),
    func.sum(case([(Tasks.complete == True, 1)], else_=0)).label("x"),
    func.sum(case([(and_(Tasks.deadline != None, Tasks.completeDate != None, Tasks.deadline > Tasks.completeDate), 1)], else_=0)).label("y"),
    func.count(Tasks.id).label("total"),
    ).join(Goals, Projects.goals).outerjoin(Strategies, Goals.strategies).outerjoin(Tasks, Strategies.tasks).group_by(Projects.id,Goals.id).filter(Projects.id == name) )
    if request.method == 'POST' and  gform.submit.data:
        if gform.validate() == False:
            flash('Failed Field validation.')
            flash_errors(gform)
            return redirect(url_for('project_outline', name=name))
        else:
            p=models.Goals(goal=gform.goal.data,proj=project)
            db.session.add(p)
            db.session.commit()
            return redirect(url_for('project_outline', name=name))
    if request.method == 'POST' and  delete_form.submitd.data:
        pstratrow = delete_form.row_id.data
        pstrat=models.Goals.query.filter_by(id=pstratrow).first()
        db.session.delete(pstrat)
        db.session.commit()
        return redirect(url_for('project_outline',name=name))            
    # if request.method == 'POST' and  delete_form.submit.data:
    #     delete_row=
    return render_template("index_for_goal.html",project=project,G=G,gform=gform,P=P,zipit=zip(G,q_sum),delete_form=delete_form)
开发者ID:chetstar,项目名称:projectmgmtWindows,代码行数:33,代码来源:views.py


示例10: _repayments

    def _repayments(self):
        today_repayments = Plan.query.filter(
            cast(Plan.plan_time, Date) == date.today(),
            Plan.status == get_enum('PLAN_PENDING')
        ).order_by('plan_time desc').limit(10)

        today_repay_amount = db_session.query(
            func.sum(Plan.amount)
        ).filter(
            cast(Plan.plan_time, Date) == date.today(),
            Plan.status == get_enum('PLAN_PENDING')
        ).scalar()

        if not today_repay_amount:
            today_repay_amount = 0

        total_repay_amount = db_session.query(
            func.sum(Plan.amount)
        ).filter(Plan.status == get_enum('PLAN_PENDING')).scalar()

        if not total_repay_amount:
            total_repay_amount = 0

        app.jinja_env.globals['today_repay_amount'] = today_repay_amount
        app.jinja_env.globals['total_repay_amount'] = total_repay_amount
        app.jinja_env.globals['today_repayments'] = today_repayments
开发者ID:xxguo,项目名称:leopard,代码行数:26,代码来源:__init__.py


示例11: allocation

def allocation():
    loc = "nav-allocation"
    if request.method == "POST" and request.form["action"] == "insert":
        #insert new allocation
        amount = request.form["amount"]
        category_id = request.form["categoryid"]
        allocation = Transaction(g.user.id, amount, "Allocation", category_id)
        db.session.add(allocation)
        db.session.commit()
        success = (True if allocation.id != -1 else False)
        return render_template("allocation.html", success = success, locid = loc)
    elif request.method == "POST" and request.form["action"] == "add":
        #show add allocation
        return render_template("allocation.html", action = "add", net_income = net_income(), category = Category.query.filter_by(category_type="Expense"),  locid = loc)
    else:
        #show allocation list
        allocation_total = 0
        qry = db.session.query(Transaction, func.sum(Transaction.amount).label("total_amount")).filter_by(transaction_type="Allocation").filter_by(user_id=g.user.id)
        for _res in qry.all():
            allocation_total = _res.total_amount

        percentage_list = []

        qry = db.session.query(Transaction, Category, func.sum(Transaction.amount).label("total_amount")).filter_by(transaction_type="Allocation").filter_by(user_id=g.user.id).join(Category).group_by(Category.description)
        for _res in qry.all():
            a = { "percent" : int(round(((_res.total_amount / allocation_total) * 100))), "description" : _res.Category.description, "amount" : _res.total_amount }
            percentage_list.append(a)
            
        rs = db.session.query(Transaction, Category).filter_by(transaction_type="Allocation").filter_by(user_id=g.user.id).join(Category)
        return render_template("allocation.html", action = "show", allocation = rs, percentage_list=percentage_list, locid = loc)
开发者ID:nicopineda,项目名称:somewebapp,代码行数:30,代码来源:app.py


示例12: _columns

    def _columns(self, total_row=False):
        columns = (
            self._column_helper("rations", "male", "st"),
            self._column_helper("rations", "female", "st"),
            self._column_helper("rations", "male", "sc"),
            self._column_helper("rations", "female", "sc"),
            self._column_helper("rations", "male", "others"),
            self._column_helper("rations", "female", "others"),
            self._column_helper("rations", "male", "disabled"),
            self._column_helper("rations", "female", "disabled"),
            self._column_helper("rations", "male", "minority"),
            self._column_helper("rations", "female", "minority"),
            self._column_helper("absent", "male"),
            self._column_helper("absent", "female"),
            self._column_helper("partial", "male"),
            self._column_helper("partial", "female"),
            self._column_helper("rations", "migrant", "male"),
            self._column_helper("rations", "migrant", "female"),
            func.count(self.table.c.case_id).filter(
                self.table.c.sex == 'M').label("child_count_male"),
            func.count(self.table.c.case_id).filter(
                self.table.c.sex == 'F').label("child_count_female"),
            func.sum(self.table.c.num_rations_distributed).filter(
                self.table.c.sex == 'M').label("thr_total_rations_male"),
            func.sum(self.table.c.num_rations_distributed).filter(
                self.table.c.sex == 'F').label("thr_total_rations_female"),
        )

        if not total_row:
            return (self.table.c.awc_id.label("owner_id"),) + columns

        return columns
开发者ID:kkrampa,项目名称:commcare-hq,代码行数:32,代码来源:ucr.py


示例13: child_victimisation_worksheet

    def child_victimisation_worksheet(self, wb):
        from dexter.models.views import DocumentChildrenView

        ws = wb.add_worksheet("child_secondary_victimisation")

        rows = self.filter(
            db.session.query(
                func.sum(
                    DocumentChildrenView.c.secondary_victim_source == "secondary-victim-source", type_=Integer
                ).label("secondary_victim_source"),
                func.sum(
                    DocumentChildrenView.c.secondary_victim_identified == "secondary-victim-identified", type_=Integer
                ).label("secondary_victim_identified"),
                func.sum(
                    DocumentChildrenView.c.secondary_victim_victim_of_abuse == "secondary-victim-abused", type_=Integer
                ).label("secondary_victim_victim_of_abuse"),
                func.sum(
                    DocumentChildrenView.c.secondary_victim_source_identified_abused
                    == "secondary-victim-source-identified-abused",
                    type_=Integer,
                ).label("secondary_victim_source_identified_abused"),
            ).join(Document)
        ).all()
        if not rows:
            return

        d = rows[0]._asdict()
        data = [[k, d[k]] for k in sorted(d.keys(), key=len)]
        ws.add_table(
            0,
            0,
            len(data),
            1,
            {"name": "ChildSecondaryVictimisation", "data": data, "columns": [{"header": ""}, {"header": "count"}]},
        )
开发者ID:Code4SA,项目名称:mma-dexter,代码行数:35,代码来源:xlsx_export.py


示例14: strategy_outline

def strategy_outline(name,goal):
    P=models.Projects.query.all()
    project=models.Projects.query.filter_by(id=name).first() 
    pgoal=models.Goals.query.filter_by(id=goal).first() 
    S=pgoal.strategies.all()
    sform=strategy_form(request.values)
    delete_form=DeleteRow_form()
    q_sum = (db.session.query(
    Projects.id.label("project_id"),
    func.sum(case([(Tasks.complete == True, 1)], else_=0)).label("x"),
    func.sum(case([(and_(Tasks.deadline != None, Tasks.completeDate != None, Tasks.deadline > Tasks.completeDate), 1)], else_=0)).label("y"),
    func.count(Tasks.id).label("total"),
    Strategies.id.label("strategy_id"),
    Goals.id.label("goal_id"),
    ).join(Goals, Projects.goals).outerjoin(Strategies, Goals.strategies).outerjoin(Tasks, Strategies.tasks).group_by(Projects.id,Goals.id,Strategies.id).filter(Goals.id == goal) )
    if request.method == 'POST' and sform.submit.data:
        print sform.validate()
        if sform.validate() == False:
            flash('Failed Field validation.')
            flash_errors(sform)
            return redirect(url_for('strategy_outline',name=name,goal=goal))
        else:
            p=models.Strategies(strategy=sform.strategy.data,goa=pgoal)
            db.session.add(p)
            db.session.commit()
            return redirect(url_for('strategy_outline',name=name,goal=goal))
    if request.method == 'POST' and  delete_form.submitd.data:
        pstratrow = delete_form.row_id.data
        pstrat=models.Strategies.query.filter_by(id=pstratrow).first()
        db.session.delete(pstrat)
        db.session.commit()
        return redirect(url_for('strategy_outline',name=name,goal=goal))
    return render_template("index_for_strategy.html",project=project,S=S,sform=sform,pgoal=pgoal,P=P,zipit=zip(S,q_sum),delete_form=delete_form)
开发者ID:chetstar,项目名称:projectmgmtWindows,代码行数:33,代码来源:views.py


示例15: execute

 def execute(mk_db):
     log.msg("start flow stat task..")
     db = mk_db()
     try:
         nodes = db.query(models.SlcNode)
         for node in nodes:
             r = db.query(
                 func.sum(models.SlcRadOnline.input_total).label("input_total"),
                 func.sum(models.SlcRadOnline.output_total).label("output_total")
             ).filter(
                 models.SlcRadOnline.account_number == models.SlcRadAccount.account_number,
                 models.SlcRadAccount.member_id == models.SlcMember.member_id,
                 models.SlcMember.node_id == node.id
             ).first()
             if r:
                 stat = models.SlcRadFlowStat()
                 stat.node_id = node.id
                 stat.stat_time = int(time.time())
                 stat.input_total = r.input_total
                 stat.output_total = r.output_total
                 db.add(stat)
         db.commit()
         log.msg("flow stat task done")
     except  Exception as err:
         db.rollback()
         log.err(err,'flow_stat_job err')
     finally:
         db.close()
开发者ID:ninetian,项目名称:ToughRADIUS,代码行数:28,代码来源:tasks.py


示例16: single_order_list

def single_order_list(id):
    order_list = database.DbOrderList.query.get(id)

    orders = []
    customers = []

    if order_list is None:
        flash('This order list does not exist')
    else:
        orders = database.DbOrder.query.filter_by(list_id=id).all()

        # count_payed = case([(database.DbOrderItem.payed,
        #                      database.DbItem.price * database.DbOrderItem.quantity)],
        #                    else_=0)

        # Very similar to query in single_order, could re-use code
        customers = (db.session.query(func.sum(database.DbOrderItem.quantity).label('quantity'),
                                      func.sum(database.DbItem.price * database.DbOrderItem.quantity).label('total_price'),
                                      # func.sum(count_payed).label('payed'),
                                      database.User)
                     .join(database.DbOrder)
                     .join(database.DbOrderList)
                     .join(database.DbItem)
                     .filter(database.DbOrderList.id == order_list.id)
                     .join(database.User)
                     .group_by(database.User.id)
                     .all())

    return render_template('order_list_single.html',
                           list=order_list,
                           orders=orders,
                           customers=customers)
开发者ID:Adverpol,项目名称:eco-basket,代码行数:32,代码来源:views.py


示例17: get_cash_flows

def get_cash_flows():
    date_range_filter_schema = DateRangeFilterSchema().load(request.args)
    if date_range_filter_schema.errors:
        return {'errors': date_range_filter_schema.errors}, 400

    cash_flow_schema = CashFlowSchema()

    amounts = db.session.query(
        func.sum(Record.amount).label("cash_flow"),
        func.sum(
            case([(Record.record_type == Record.RECORD_TYPE_INCOME, Record.amount)], else_=0)
        ).label('income'),
        func.sum(
            case([(Record.record_type == Record.RECORD_TYPE_EXPENSE, Record.amount)], else_=0)
        ).label('expense'),
        func.date_trunc('month', Record.date).label("date"),
    ).group_by(
        func.date_trunc('month', Record.date)
    ).order_by(
        func.date_trunc('month', Record.date)
    )

    if 'date_from' in date_range_filter_schema.data:
        amounts = amounts.filter(Record.date >= date_range_filter_schema.data['date_from'])

    if 'date_to' in date_range_filter_schema.data:
        amounts = amounts.filter(Record.date < date_range_filter_schema.data['date_to'])

    return {'objects': cash_flow_schema.dump(amounts, many=True).data}
开发者ID:monetario,项目名称:core,代码行数:29,代码来源:balance.py


示例18: get_taxi_data_distribution

def get_taxi_data_distribution(color):
    if color != 'all':
        taxi_type = COLOR_CODE[color]

    # TODO:
    # By default, we will just return a key-value pair of month and count
    out_data = []
    if 'interval' in request.args:
        if request.args['interval'] == 'month':
            # distribution by month
            # NOTE: Using a different mechanism now!!!!!!
            for i in range(1, 13):
                # out_data.append({
                #     "date": i,
                #     "count": session.query(func.sum(TripStats.total_record_cnt)).filter(TripStats.taxi_type == taxi_type, extract('month', TripStats.datetime) == i).first()[0]
                # })
                out_data.append({
                    "date": i,
                    "type": 2,
                    "count": session.query(func.sum(TripStats.total_record_cnt)).filter(TripStats.taxi_type == 2, extract('month', TripStats.datetime) == i).first()[0]
                })
                out_data.append({
                    "date": i,
                    "type": 1,
                    "count": session.query(func.sum(TripStats.total_record_cnt)).filter(TripStats.taxi_type == 1, extract('month', TripStats.datetime) == i).first()[0]
                })
        elif request.args['interval'] == 'week':
            # distribution by weekday
            yellow_trips = TripStats.query.filter(TripStats.taxi_type == 2).all()
            green_trips = TripStats.query.filter(TripStats.taxi_type == 1).all()
            mid_data_yellow = {}
            mid_data_green = {}
            for i in range(0, 8):
                for trip in yellow_trips:
                    if i in mid_data_yellow and trip.datetime.weekday() == i:
                        mid_data_yellow[i] += trip.total_record_cnt
                    elif trip.datetime.weekday() == i:
                        mid_data_yellow[i] = trip.total_record_cnt
            for i in range(0, 8):
                for trip in green_trips:
                    if i in mid_data_green and trip.datetime.weekday() == i:
                        mid_data_green[i] += trip.total_record_cnt
                    elif trip.datetime.weekday() == i:
                        mid_data_green[i] = trip.total_record_cnt

            for key, val in mid_data_yellow.items():
                out_data.append({
                    "date": key,
                    "type": 2,
                    "count": val
                })
            for key, val in mid_data_green.items():
                out_data.append({
                    "date": key,
                    "type": 1,
                    "count": val
                })

    return return_json(out_data)
开发者ID:benjamin21st,项目名称:bigdata_2016,代码行数:59,代码来源:views.py


示例19: analytics_time_spent_to_music

def analytics_time_spent_to_music():
    return dict(users=[
        (db.session.query(User).get(user_id), timedelta_in_words(int(time_spent), 2))
        for user_id, time_spent in db.session.query(Scrobble.user_id, func.sum(ApproximateTrackLength.length)).\
                                              outerjoin((ApproximateTrackLength, Scrobble.approximate_track_length)).\
                                              group_by(Scrobble.user_id).\
                                              order_by(-func.sum(ApproximateTrackLength.length))
    ])
开发者ID:Erkan-Yilmaz,项目名称:last.fm.thelogin.ru,代码行数:8,代码来源:analytics.py


示例20: __call__

 def __call__(self, column_clause, cuboid=None):
     if cuboid and cuboid.fact_count_column is not None:
         count = func.sum(cuboid.fact_count_column)
         return case([(count == 0, 0)], else_=(
             func.sum(column_clause * cuboid.fact_count_column) /
             cast(count,
                  types.Numeric)))
     return func.avg(column_clause)
开发者ID:Kozea,项目名称:pypet,代码行数:8,代码来源:aggregates.py



注:本文中的sqlalchemy.sql.func.sum函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python functions.count函数代码示例发布时间:2022-05-27
下一篇:
Python func.now函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap