如何在一列上有group_by,在另一列上有order_by,在第三列上有过滤器?

时间:2017-04-10 08:14:12

标签: sql sqlalchemy flask-sqlalchemy

这是表格:

class APIBackoffInterrupt(Base):
    """
    When a user calls a Google API method, and it returns 403 or 429, we should apply an exponential backoff
    """
    __tablename__ = 'backoff_interrupt'
    _id = Column(Unicode(36), primary_key=True)
    user_id = Column(Unicode(36))
    date_created_utc = Column(DateTime)
    expiry_date_utc = Column(DateTime, nullable=True)
    exponent = Column(Integer, default=-1)

我想获得所有唯一的user_id,按date_created_utc(desc)排序,其中expiry_date_utc是<现在的utc。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

select distinct user_id 
 from backoff_interrupt
   where expiry_date_utc <getdate() 
 order by date_created_utc desc

检查一下: 更新:

select * into #temp from backoff_interrupt  
 where expiry_date_utc <getdate()
 order by date_created_utc desc 

  select distinct user_Id from #temp

 drop #temp

答案 1 :(得分:0)

    q1 = (session.query(APIBackoffInterrupt,
                        func.rank().over(order_by=desc(APIBackoffInterrupt.date_created_utc),
                                         partition_by=APIBackoffInterrupt.user_id).label('rnk'))
          ).subquery()
    q2 = (session.query(q1)
          .filter(q1.c.rnk == 1)
          .filter(q1.c.expiry_date_utc < datetime.datetime.utcnow())
          )