当前位置: 首页>>代码示例>>Python>>正文


Python func.sum函数代码示例

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


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

示例1: stockcheck

def stockcheck(request, info, session):
    buylist = []
    depts = session.query(Department).order_by(Department.id).all()
    if request.method == "POST":
        form = StockCheckForm(depts, request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            ahead = datetime.timedelta(days=cd["weeks_ahead"] * 7)
            behind = datetime.timedelta(days=cd["months_behind"] * 30.4)
            min_sale = cd["minimum_sold"]
            dept = int(cd["department"])
            q = (
                session.query(StockType, func.sum(StockOut.qty) / behind.days)
                .join(StockItem)
                .join(StockOut)
                .options(lazyload(StockType.department))
                .options(lazyload(StockType.unit))
                .options(undefer(StockType.instock))
                .filter(StockOut.removecode_id == "sold")
                .filter((func.now() - StockOut.time) < behind)
                .filter(StockType.dept_id == dept)
                .having(func.sum(StockOut.qty) / behind.days > min_sale)
                .group_by(StockType)
            )
            r = q.all()
            buylist = [(st, "{:0.1f}".format(sold), "{:0.1f}".format(sold * ahead.days - st.instock)) for st, sold in r]
            buylist.sort(key=lambda l: float(l[2]), reverse=True)
    else:
        form = StockCheckForm(depts)
    return ("stockcheck.html", {"form": form, "buylist": buylist})
开发者ID:sde1000,项目名称:quicktill,代码行数:30,代码来源:views.py

示例2: overview

def overview():
    uquery = lambda: session.session.query(User)

    entries = [{"title": "Nutzer in Datenbank",
                "href": None,
                "number": uquery().count()},
               {"title": "Mitglieder",
                "href": None,
                "number": uquery().join(Membership).filter(
                                Membership.group == config.member_group,
                                Membership.active())
                           .count()},
               {"title": "Nicht bezahlt",
                "href": None,
                "number": uquery().join(User.account)
                           .join(Split)
                           .group_by(User.id)
                           .having(func.sum(Split.amount) > 0)
                           .count()},
               {"title": "Nicht bezahlt (Mitglieder)",
                "href": "#",
                "number": uquery().join(Membership).filter(
                                Membership.group == config.member_group,
                                Membership.active())
                           .join(User.account)
                           .join(Split)
                           .group_by(User.id)
                           .having(func.sum(Split.amount) > 0)
                           .count()}]
    return render_template("user/user_overview.html", entries=entries)
开发者ID:agdsn,项目名称:pycroft,代码行数:30,代码来源:__init__.py

示例3: accounts

def accounts():
    month_year = request.args.get('month_year')
    month_years = (db.session.query(func.strftime("%m-%Y", Transaction.date))
                   .select_from(Transaction)
                   .distinct()
                   .order_by(func.strftime("%Y-%m", Transaction.date))
                   .all()
                   )
    month_years = [each[0] for each in month_years]

    accounts_query = (db.session.query(
        func.sum(Transaction.withdrawal),
        func.sum(Transaction.deposit),
        Account.full_title)
                .select_from(Account)
                .outerjoin(Transaction)
                .group_by(Account.id)
                .order_by(Account.full_title)
                )

    if month_year:
        accounts_query = accounts_query.filter(func.strftime("%m-%Y", Transaction.date) == month_year)

    accounts = accounts_query.all()
                

    def relabel(account):
        return {"withdrawal": account[0],
                "deposit": account[1],
                "full_title": account[2]}
                
    accounts = [relabel(account) for account in accounts]
    return render_template('accounts.html', accounts=accounts, title="Accounts", month_year=month_year, month_years=month_years)
开发者ID:noisecapella,项目名称:personal_ledger,代码行数:33,代码来源:views.py

示例4: has_exceeded_traffic

def has_exceeded_traffic(user):
    """
    The function calculates the balance of the users traffic.
    :param user: The user object which has to be checked.
    :return: True if the user has more traffic than allowed and false if he
    did not exceed the limit.
    """
    result = session.session.query(
        User.id,
        (func.max(TrafficGroup.traffic_limit) * 1.10) < func.sum(TrafficVolume.size).label("has_exceeded_traffic")
    ).join(
        User.active_traffic_groups
    ).join(
        User.user_hosts
    ).join(
        Host.ips
    ).join(
        Ip.traffic_volumes
    ).filter(
        User.id == user.id
    ).group_by(
        User.id
    ).first()

    if result is not None:
        return result.has_exceeded_traffic
    else:
        return False
开发者ID:lukasjuhrich,项目名称:pycroft,代码行数:28,代码来源:user.py

示例5: amount

 def amount(self, account):
     query = (
         self.session
         .query(func.sum(Ledger.amount))
         .filter(Ledger.account == account)
     )
     return query.scalar() or 0
开发者ID:NSAKHAN,项目名称:aggregation-benchmark,代码行数:7,代码来源:original.py

示例6: group_hot_value

def group_hot_value(group):
    hot = db.session.query(func.sum(Hot.number))\
        .filter(Group.active == True,
                Post.group_id == group.id,
                Post.id == Hot.post_id) \
        .group_by(Group.id)\
        .first()[0]
    return hot
开发者ID:rafagonc,项目名称:share,代码行数:8,代码来源:group_queries.py

示例7: get_done

    def get_done(self):
        total = (
            DBSession.query(func.sum(ST_Area(Task.geometry)))
            .filter(Task.project_id == self.id, Task.cur_state.has(TaskState.state != TaskState.state_removed))
            .scalar()
        )

        done = (
            DBSession.query(func.sum(ST_Area(Task.geometry)))
            .filter(Task.project_id == self.id, Task.cur_state.has(TaskState.state == TaskState.state_done))
            .scalar()
        )

        if not done:
            done = 0

        return round(done * 100 / total) if total != 0 else 0
开发者ID:nyampire,项目名称:osm-tasking-manager2,代码行数:17,代码来源:models.py

示例8: hottest_users

def hottest_users():
    users_and_ids = db.session.query(func.sum(Hot.number), User.id).filter(User.id == Post.user_id, Post.id == Hot.post_id).group_by(User.id).order_by(func.sum(Hot.number)).limit(3).all()
    users = []
    for user_and_id in users_and_ids:
        user = user_from_id(user_and_id[1])
        user.__setattr__('hot', user_and_id[0])
        users.append(user)
    return users
开发者ID:rafagonc,项目名称:share,代码行数:8,代码来源:user_queries.py

示例9: get_validated

    def get_validated(self):
        total = (
            DBSession.query(func.sum(ST_Area(Task.geometry)))
            .filter(Task.project_id == self.id, Task.cur_state.has(TaskState.state != TaskState.state_removed))
            .scalar()
        )

        validated = (
            DBSession.query(func.sum(ST_Area(Task.geometry)))
            .filter(Task.project_id == self.id, Task.cur_state.has(TaskState.state == TaskState.state_validated))
            .scalar()
        )

        if not validated:
            validated = 0

        return round(validated * 100 / total) if total != 0 else 0
开发者ID:nyampire,项目名称:osm-tasking-manager2,代码行数:17,代码来源:models.py

示例10: refund

    def refund(self, invoice, amount):
        """Refund the invoice

        """
        Transaction = tables.Transaction
        tx_model = self.factory.create_transaction_model()
        transactions = []

        self.get(invoice.guid, with_lockmode='update')

        if invoice.status != self.statuses.SETTLED:
            raise InvalidOperationError('You can only refund a settled invoice')

        refunded_amount = (
            self.session.query(
                func.coalesce(func.sum(Transaction.amount), 0)
            )
            .filter(
                Transaction.invoice == invoice,
                Transaction.transaction_type == TransactionModel.types.REFUND,
                Transaction.submit_status.in_([
                    TransactionModel.submit_statuses.STAGED,
                    TransactionModel.submit_statuses.RETRYING,
                    TransactionModel.submit_statuses.DONE,
                ])
            )
        ).scalar()
        # Make sure do not allow refund more than effective amount
        if refunded_amount + amount > invoice.effective_amount:
            raise InvalidOperationError(
                'Refund total amount {} + {} will exceed invoice effective amount {}'
                .format(
                    refunded_amount,
                    amount,
                    invoice.effective_amount,
                )
            )

        # the settled transaction
        settled_transaction = (
            self.session.query(Transaction)
            .filter(
                Transaction.invoice == invoice,
                Transaction.transaction_type == TransactionModel.types.DEBIT,
                Transaction.submit_status == TransactionModel.submit_statuses.DONE,
            )
        ).one()

        # create the refund transaction
        transaction = tx_model.create(
            invoice=invoice,
            transaction_type=TransactionModel.types.REFUND,
            amount=amount,
            reference_to=settled_transaction,
        )
        transactions.append(transaction)
        return transactions
开发者ID:Imaxinacion,项目名称:billy,代码行数:57,代码来源:invoice.py

示例11: hottest_groups

def hottest_groups(user):
    groups = db.session.query(Group)\
            .outerjoin((Post, Post.group_id == Group.id),
                        (Hot, Post.id == Hot.post_id)) \
        .filter(Group.active == True)\
        .group_by(Group.id)\
        .order_by(func.sum(Hot.number))\
        .limit(3)\
        .all()
    return groups
开发者ID:rafagonc,项目名称:share,代码行数:10,代码来源:group_queries.py

示例12: get_stats

 def get_stats(self, name, limit=100, total=False):
     q = (db.session.query(Stats.date, func.sum(Stats.value).label("value"))
         .filter(
             place_parents.c.parent_id==self.id,
             place_parents.c.child_id==Stats.place_id,
             Stats.name==name)
         .group_by(Stats.date)
         .order_by(Stats.date)
         .limit(limit))
     return q.all()
开发者ID:RaghavPro,项目名称:cleansweep,代码行数:10,代码来源:models.py

示例13: download_size

 def download_size(self):
     from ututi.model import File, FileDownload
     download_size = meta.Session.query(func.sum(File.filesize))\
         .filter(FileDownload.file_id==File.id)\
         .filter(FileDownload.user==self)\
         .filter(FileDownload.range_start==None)\
         .filter(FileDownload.range_end==None)\
         .scalar()
     if not download_size:
         return 0
     return int(download_size)
开发者ID:nous-consulting,项目名称:ututi,代码行数:11,代码来源:users.py

示例14: total_adjustment_amount

    def total_adjustment_amount(self):
        """Sum of total adjustment amount

        """
        from sqlalchemy import func
        session = object_session(self)
        return (
            session.query(func.coalesce(func.sum(Adjustment.amount), 0))
            .filter(Adjustment.invoice_guid == self.guid)
            .scalar()
        )
开发者ID:remotesyssupport,项目名称:billy,代码行数:11,代码来源:tables.py

示例15: get_stats

def get_stats(project):
    """
    the changes to create a chart with
    """

    total = DBSession.query(func.sum(ST_Area(Task.geometry))) \
        .filter(
            Task.cur_state.has(TaskState.state != TaskState.state_removed),
            Task.project_id == project.id
        ) \
        .scalar()

    subquery = DBSession.query(
        TaskState.state,
        TaskState.date,
        ST_Area(Task.geometry).label('area'),
        func.lag(TaskState.state).over(
            partition_by=(
                TaskState.task_id,
                TaskState.project_id
            ),
            order_by=TaskState.date
        ).label('prev_state')
    ).join(Task).filter(
        TaskState.project_id == project.id,
        TaskState.state != TaskState.state_ready) \
     .order_by(TaskState.date)

    tasks = subquery.all()
    log.debug('Number of tiles: %s', len(tasks))
    stats = [[project.created.isoformat(), 0, 0]]
    done = 0
    validated = 0

    # for every day count number of changes and aggregate changed tiles
    for task in tasks:
        if task.state == TaskState.state_done:
            done += task.area
        if task.state == TaskState.state_invalidated:
            if task.prev_state == TaskState.state_done:
                done -= task.area
            elif task.prev_state == TaskState.state_validated:
                validated -= task.area
        if task.state == TaskState.state_validated:
            validated += task.area
            done -= task.area

        # append a day to the stats and add total number of 'done' tiles and a
        # copy of a current tile_changes list
        stats.append([task.date.isoformat(), done, validated])

    return {"total": total, "stats": stats}
开发者ID:KaiBot3000,项目名称:osm-tasking-manager2,代码行数:52,代码来源:project.py


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