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

Python sql.label函数代码示例

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

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



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

示例1: totalList

def totalList():
    if not redis.llen('rank:total'):
        total_row = db_session.query(
            User.id,
            User.username,
            label('number', func.count(Investment.amount)),
            label('total_amount', func.sum(Investment.amount))
        ).filter(
            Investment.user_id == User.id,
        ).group_by(User.id).order_by(
            func.sum(Investment.amount).desc()
        ).limit(15).all()

        total_list = []

        for i in total_row:
            i = dict(zip(i.keys(), i))
            data = {
                'id': i['id'],
                'username': i['username'],
                'total_amount': float(i['total_amount']),
                'number': i['number']
            }
            total_list.append(data)
            redis.rpush('rank:total', json.dumps(data))
        redis.expire('rank:total', 3600)
    else:
        total_list = [json.loads(i.decode()) for i in redis.lrange('rank:total', 0, redis.llen('rank:total'))]

    return total_list
开发者ID:xxguo,项目名称:leopard,代码行数:30,代码来源:rank.py


示例2: weekList

def weekList():
    if not redis.llen('rank:week'):
        rows = db_session.query(
            User.id,
            User.username,
            label('number', func.count(Investment.amount)),
            label('total_amount', func.sum(Investment.amount))
        ).filter(
            Investment.user_id == User.id,
            cast(Investment.added_at, Date) <= datetime.datetime.today(),
            cast(Investment.added_at, Date) >= datetime.datetime.today() -
            datetime.timedelta(weeks=1)
        ).group_by(User.id).order_by(
            func.sum(Investment.amount).desc()
        ).limit(15).all()

        rank_list = []

        for i in rows:
            i = dict(zip(i.keys(), i))
            data = {
                'id': i['id'],
                'username': i['username'],
                'total_amount': float(i['total_amount']),
                'number': i['number']
            }
            rank_list.append(data)
            redis.rpush('rank:week', json.dumps(data))
        redis.expire('rank:week', 3600)
    else:
        rank_list = [json.loads(i.decode()) for i in redis.lrange('rank:week', 0, redis.llen('rank:week'))]

    return rank_list
开发者ID:xxguo,项目名称:leopard,代码行数:33,代码来源:rank.py


示例3: select_tz

    def select_tz (self):
        """Select time zones and other related fields from database.

        Selects count of messages, count of distinct senders,
        time zone.

        Returns
        -------

        Query object

        """

        query = self.add_columns(
            label("tz",
                  ((DB.Messages.first_date_tz.op('div')(3600) + 36) % 24) - 12),
            label("messages",
                  func.count(func.distinct(DB.Messages.message_ID))),
            label("authors",
                  func.count(func.distinct(DB.MessagesPeople.email_address))))
        self.joined.append (DB.Messages)
        if DB.MessagesPeople not in self.joined:
            query = query.join (DB.MessagesPeople)
            self.joined.append (DB.MessagesPeople)
            query = query.filter (DB.MessagesPeople.type_of_recipient == "From")
        return query
开发者ID:VizGrimoire,项目名称:GrimoireLib,代码行数:26,代码来源:mls_tz.py


示例4: select_personsdata

    def select_personsdata(self, kind):
        """Adds columns with persons data to select clause.

        Adds people.name, people.email to the select clause of query.
        Does not join new tables.

        Parameters
        ----------

        kind: {"authors", "committers"}
           Kind of person to select

        Returns
        -------

        SCMObject: Result query, with new fields: id, name, email        

        """

        query = self.add_columns (label("person_id", DB.People.id),
                                  label("name", DB.People.name),
                                  label('email', DB.People.email))
        if kind == "authors":
            person = DB.SCMLog.author_id
        elif kind == "committers":
            person = DB.SCMLog.committer_id
        else:
            raise Exception ("select_personsdata: Unknown kind %s." \
                             % kind)
        if DB.SCMLog in self.joined:
            query = query.filter (DB.People.id == person)
        else:
            self.joined.append (DB.SCMLog)
            query = query.join (DB.SCMLog, DB.People.id == person)
        return query
开发者ID:VizGrimoire,项目名称:GrimoireLib,代码行数:35,代码来源:scm.py


示例5: get_query

def get_query(qtype = 'none', qobject = 'none'):

    if qtype != 'none' and qobject != 'none':

        # built queries for specified subset of patients
        query = db.session.query(label('sid', qobject.c.patient_sid),
                                 label('value_d', qobject.c.double_value),
                                 label('value_s', qobject.c.string_value),
                                 label('attribute', qobject.c.attribute_value))

    elif qtype == 'count' and qobject == 'none':

        # count of patients
        query = db.session.query(distinct(Clinical.patient_sid).label('sid'))


    else:

        # entire population
        query = db.session.query(distinct(Clinical.patient_sid).label('sid'),
                                 literal_column("'complement'").label('attribute'),
                                 literal_column("'0'").label('value_d'),
                                 literal_column("'null'").label('value_s'))


    db.session.commit()
    db.session.close()

    return query
开发者ID:GregSilverman,项目名称:cohort_rest_api,代码行数:29,代码来源:sqla_methods.py


示例6: pending_requests_for_user

    def pending_requests_for_user(self, user):
        # type: (str) -> List[UserGroupRequest]
        requester = aliased(User)
        on_behalf_of = aliased(User)
        sql_requests = self.session.query(
            Request.id,
            Request.status,
            label("requester", requester.username),
            Group.groupname,
            label("on_behalf_of", on_behalf_of.username),
        ).filter(
            Request.on_behalf_obj_type == OBJ_TYPES["User"],
            Request.on_behalf_obj_pk == on_behalf_of.id,
            Request.requester_id == requester.id,
            Request.requesting_id == Group.id,
            Request.status == "pending",
        )

        requests = []
        for sql_request in sql_requests:
            request = UserGroupRequest(
                id=sql_request.id,
                user=sql_request.on_behalf_of,
                group=sql_request.groupname,
                requester=sql_request.requester,
                status=sql_request.status,
            )
            requests.append(request)
        return requests
开发者ID:dropbox,项目名称:grouper,代码行数:29,代码来源:group_request.py


示例7: select_listpersons

    def select_listpersons(self, kind = "all"):
        """Select a list of persons (authors, committers)

        - kind: kind of person to select
           authors: authors of commits
           committers: committers of commits
           all: authors and committers

        Returns a SCMQuery object, with (id, name, email) selected.
        """

        query = self.add_columns (label("id", func.distinct(People.id)),
                                  label("name", People.name),
                                  label('email', People.email))
        if kind == "authors":
            return query.join (SCMLog, People.id == SCMLog.author_id)    
        elif kind == "committers":
            return query.join (SCMLog, People.id == SCMLog.committer_id)    
        elif kind == "all":
            return query.join (SCMLog,
                               People.id == SCMLog.author_id or
                               People.id == SCMLog.committer_id)
        else:
            raise Exception ("select_listpersons: Unknown kind %s." \
                             % kind)
开发者ID:virusu,项目名称:PFC_old,代码行数:25,代码来源:scm_query.py


示例8: group_by_period

    def group_by_period (self):
        """Group by time period (per month)"""

        return self \
            .add_columns (label("month", func.month(SCMLog.date)),
                          label("year", func.year(SCMLog.date))) \
            .group_by("month", "year").order_by("year", "month")
开发者ID:virusu,项目名称:PFC_old,代码行数:7,代码来源:scm_query.py


示例9: query_start

def query_start (changes = None):
    """Produce a query for selecting chnage start events.

    The query will select "date" as the date for the event, and
    "change" for the change number. The date is calculated as
    the date of the first revision.

    Parameters
    ----------

    changes: list of int
        List of change numbers to consider.

    Returns
    -------

    query_gerrit.query: produced query

    """

    q = session.query(
        label ("date", func.min(DB.Revision.date)),
        label ("change", DB.Change.number),
        ) \
        .join(DB.Change)
    q = q.group_by(DB.Change.uid)
    if changes is not None:
        q = q.filter(DB.Change.number.in_(changes))
    return q
开发者ID:jgbarah,项目名称:revisor,代码行数:29,代码来源:report.py


示例10: calc_duration_changes

def calc_duration_changes(max):
    """Calculate duration of changes (time from created to updated).

    This will print sumary stats about the duration of the
    changes in the review system, and will show some of them.

    Parameters
    ----------

    max: int
        Max number of changes to show.

    """

    res = session.query(
        label ("number",
               DB.Change.number),
        label ("start",
               DB.Change.created),
        label ("finish",
               DB.Change.updated),
        ) \
        .filter (DB.Change.created < DB.Change.updated) \
        .order_by (desc (func.datediff(DB.Change.updated,
                                       DB.Change.created)))
    cases = res.limit(max).all()
    for case in cases:
        print str(case.number) + ": " + str(case.start) + \
            " (start), " + str(case.finish) + " (finish) Duration: " + \
            str(case.finish - case.start)
开发者ID:jgbarah,项目名称:revisor,代码行数:30,代码来源:report.py


示例11: check_abandon_cont

def check_abandon_cont(max):
    """Check changes with an "Abandoned" but continuing with activity.

    Parameters
    ----------

    max: int
        Max number of cases to show among those violating the check.

    """

    q_abandons = session.query(
        label("id", DB.Change.uid),
        label("date", func.min(DB.Message.date)),
        label("num", DB.Change.number)
        ) \
        .select_from(DB.Change) \
        .join(DB.Message) \
        .filter (or_ (DB.Message.header == "Abandoned",
                      DB.Message.header.like ("Patch%Abandoned"))) \
        .group_by(DB.Change.uid) \
        .subquery()
    q = session.query(
        label("num", q_abandons.c.num)
        ) \
        .join(DB.Message,
              DB.Message.change_id == q_abandons.c.id) \
        .filter(DB.Message.date > q_abandons.c.date) \
        .group_by(q_abandons.c.id)
    changes = q.count()
    print "Changes abandoned, with activity after abandon (" \
        + str(changes) + "): ",
    for change in q.limit(max).all():
        print change.num
    print
开发者ID:jgbarah,项目名称:revisor,代码行数:35,代码来源:report.py


示例12: check_first_revision

def check_first_revision(max):
    """Check that changes have a first revision.

    Parameters
    ----------

    max: int
        Max number of cases to show among those violating the check.

    """

    q = session.query(
        label ("revision", DB.Revision.uid),
        ) \
        .join (DB.Change) \
        .filter (DB.Revision.number == 1) \
        .group_by (DB.Change.uid)
    print "Changes with first revision: " + str(q.count())
    first = session.query(
        label ("change", DB.Revision.change_id),
        ) \
        .filter (DB.Revision.number == 1) \
        .subquery()
    q = session.query(
        label ("change", DB.Change.number),
        ) \
        .filter (~DB.Change.uid.in_(first))
    for change in q.limit(max).all():
        print change.change
    print "Changes with no first revision: " + str(q.count())
开发者ID:jgbarah,项目名称:revisor,代码行数:30,代码来源:report.py


示例13: check_newer_dates

def check_newer_dates(max):
    """Check that dates related to a change are newer than creation date.

    This will print sumary stats about dates that are not correct,
    and will show at most max cases.

    Parameters
    ----------

    max: int
        Max number of cases to show among those violating the check.

    """

    res = session.query(
        label ("number",
               DB.Change.number),
        label ("created",
               DB.Change.created),
        label ("updated",
               DB.Change.updated)
        ) \
        .filter (DB.Change.created > DB.Change.updated) \
        .order_by (desc (func.datediff(DB.Change.created,
                                       DB.Change.updated)))
    cases = res.limit(max).all()
    for case in cases:
        print str(case.number) + ": " + str(case.created) + \
            " (created), " + str(case.updated) + " (updated) Mismatch: " + \
            str(case.created - case.updated) + ")"
    print "Total number of mismatchs: " + str(res.count())
开发者ID:jgbarah,项目名称:revisor,代码行数:31,代码来源:report.py


示例14: select_listpersons_uid

    def select_listpersons_uid(self, kind = "all"):
        """Select a list of persons (authors, committers), using uids

        - kind: kind of person to select
           authors: authors of commits
           committers: committers of commits
           all: authors and committers
        Returns a SCMQuery object, with (id, name, email) selected.
        """
        
        query = self.add_columns (label("id", func.distinct(UPeople.id)),
                                  label("name", UPeople.identifier)) \
                .join (PeopleUPeople, UPeople.id == PeopleUPeople.upeople_id)
        if kind == "authors":
            return query.join (SCMLog,
                               PeopleUPeople.people_id == SCMLog.author_id)
        elif kind == "committers":
            return query.join (SCMLog,
                               PeopleUPeople.people_id == SCMLog.committer_id)
        elif kind == "all":
            return query.join (SCMLog,
                               PeopleUPeople.people_id == SCMLog.author_id or
                               PeopleUPeople.people_id == SCMLog.committer_id)
        else:
            raise Exception ("select_listpersons_uid: Unknown kind %s." \
                             % kind)
开发者ID:virusu,项目名称:PFC_old,代码行数:26,代码来源:scm_query.py


示例15: select_listcommits

 def select_listcommits(self):
     """Select a list of commits"""
     
     if DB.SCMLog not in self.joined:
         self.joined.append(DB.SCMLog)
     return self \
         .add_columns (label("id", func.distinct(DB.SCMLog.id)),
                       label("date", DB.SCMLog.date))
开发者ID:VizGrimoire,项目名称:GrimoireLib,代码行数:8,代码来源:scm.py


示例16: repostat

def repostat(repoid = -1):
    if repoid == -1:
        return ses.query(Kuyruk.repository, Kuyruk.branch, Kuyruk.durum, label('sayi', func.count(Kuyruk.id))).group_by(Kuyruk.repository, Kuyruk.branch, Kuyruk.durum).all()
    else:
        cevap = ses.query(Repo.repo, Repo.branch).filter_by(id=repoid).one()
        c2 = ses.query(Kuyruk.repository, Kuyruk.branch, Kuyruk.durum,
                         label('sayi', func.count(Kuyruk.id))).filter_by(repository=cevap.repo , branch=cevap.branch).group_by(
            Kuyruk.repository, Kuyruk.branch, Kuyruk.durum).all()
        return c2
开发者ID:SamiBabat,项目名称:pisi-farm,代码行数:9,代码来源:farm.py


示例17: _get_nodes_from_db

 def _get_nodes_from_db(session):
     return session.query(
         label("type", literal("User")),
         label("name", User.username)
     ).filter(
         User.enabled == True
     ).union(session.query(
         label("type", literal("Group")),
         label("name", Group.groupname))
     ).filter(
         Group.enabled == True
     ).all()
开发者ID:tmildorf,项目名称:grouper,代码行数:12,代码来源:graph.py


示例18: show_summary_projects

def show_summary_projects ():
    """Summary of main stats by project (and name of projects).

    """

    q = session.query (label ("project", DB.Change.project),
                       label ("changes", func.count(DB.Change.uid))
                       ) \
                       .group_by(DB.Change.project) \
                       .order_by(desc("changes"))
    for project, changes in q.all():
        print project + ": " + str(changes)
开发者ID:jgbarah,项目名称:revisor,代码行数:12,代码来源:report.py


示例19: get_results

    def get_results(self):
        query = select([
            label('user_id', self.sql_table.c.owner_id),
            label('count', func.count(self.sql_table.c.doc_id))
        ]).where(and_(
            self.sql_table.c.type != self.cc_case_type,
            self.sql_table.c.closed == 0,
            operators.in_op(self.sql_table.c.owner_id, self.users_needing_data),
        )).group_by(
            self.sql_table.c.owner_id
        )

        return self._run_query(query)
开发者ID:dimagi,项目名称:commcare-hq,代码行数:13,代码来源:queries.py


示例20: select_listbranches

    def select_listbranches(self):
        """Select list of branches in repo

        Returns a list with a tuple (id, name) per branch
        The Actions table is used, instead of the Branches table,
        so that some filters, such as filter_period() can be used
        """

        query = self.add_columns (label("id",
                                        func.distinct(Actions.branch_id)),
                                  label("name",
                                        Branches.name))
        query = query.join(Branches)
        return query
开发者ID:virusu,项目名称:PFC_old,代码行数:14,代码来源:scm_query.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python sql.literal函数代码示例发布时间:2022-05-27
下一篇:
Python sql.join函数代码示例发布时间: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