Python SQLAlchemy-选择具有相同列值的行,不包括具有不同列值的行

Python SQLAlchemy-选择具有相同列值的行,不包括具有不同列值的行,python,sql,sqlalchemy,Python,Sql,Sqlalchemy,我对SQL/SQLAlchemy缺乏经验,正在尝试从名为Event的表中编写一个SQLAlchemy查询,数据如下: 我想选择类型等于“已查看选项卡”的行,但前提是不存在类型等于“移动视图”的具有相同会话值的行。因此,在上面的示例数据中,我希望查询返回EventId为150和154的行,而不是147的行 谢谢。试试: select e.* from event e join (select eventid, session from event gr

我对SQL/SQLAlchemy缺乏经验,正在尝试从名为Event的表中编写一个SQLAlchemy查询,数据如下:

我想选择类型等于“已查看选项卡”的行,但前提是不存在类型等于“移动视图”的具有相同会话值的行。因此,在上面的示例数据中,我希望查询返回EventId为150和154的行,而不是147的行

谢谢。

试试:

select e.*
  from event e
  join (select eventid, session
          from event
         group by eventid, session
        having sum(case when type = 'Viewed Tab' then 1 else 0 end) > 0
           and sum(case when type = 'Mobile View' then 1 else 0 end) = 0) v
    on e.eventid = v.eventid

但是,我不确定sql alchemy有哪些语法限制。

假设该表定义如下:

class Event(Base):
    __tablename__ = 'events'
    EventId = Column(Integer, primary_key=True)
    Session = Column(Integer)
    Type = Column(String)
生成所需结果的查询可以写成:

viewed = aliased(Event, name='viewed')
mobile = aliased(Event, name='mobile')
qry = (session.query(viewed)
       .filter(viewed.Type == 'Viewed Tab')
       .outerjoin(mobile, and_(
           viewed.Session == mobile.Session,
           mobile.Type == 'Mobile View')
       )
       .filter(mobile.Session == None)
       )
这将生成一个没有任何聚合的查询:

SELECT  viewed."EventId" AS "viewed_EventId",
        viewed."Session" AS "viewed_Session",
        viewed."Type" AS "viewed_Type"

FROM    events AS viewed

LEFT OUTER JOIN
        events AS mobile
    ON  viewed."Session" = mobile."Session"
    AND mobile."Type" = 'Mobile View'

WHERE   viewed."Type" = 'Viewed Tab'
    AND mobile."Session" IS NULL