[英]SQLAlchemy - Select rows with the same column values, excluding those with values from different column
I am inexperienced in SQL / SQLAlchemy, and am trying to write a SQLAlchemy query from a table called Event with data such as this: 我对SQL / SQLAlchemy缺乏经验,并试图从名为Event的表中编写一个SQLAlchemy查询,其中包含以下数据:
I would like to select the rows with Type equal to "Viewed Tab", but only if there does not exists a row with the same Session value that has a Type equal to "Mobile View". 我想选择Type等于“ Viewed Tab”的行,但前提是不存在具有相同Session值且Type等于“ Mobile View”的行。 So in the sample data above I would want the query to return the rows with EventId equal to 150 and 154, but not 147.
因此,在上面的示例数据中,我希望查询返回EventId等于150和154而不是147的行。
Thank you. 谢谢。
Assuming the table is defined as per below: 假设表定义如下:
class Event(Base):
__tablename__ = 'events'
EventId = Column(Integer, primary_key=True)
Session = Column(Integer)
Type = Column(String)
the query to produce the desired result can be written as: 产生期望结果的查询可以写成:
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)
)
This will produce a query without any aggregations: 这将产生没有任何聚合的查询:
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
Try: 尝试:
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
I'm not sure what syntax limitations there are with sql alchemy, however. 我不确定sql alchemy有什么语法限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.