SQLAlchemy: 获取分组值的最大值
P粉738346380
P粉738346380 2023-09-01 12:07:40
0
1
408
<p>我在我的Flask应用中有这个表:</p> <pre class="brush:php;toolbar:false;">class Events(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) timestamp_event = db.Column(db.DateTime, nullable=False)</pre> <p>我需要获取记录最多的那一天,包括值和日期本身的可打印格式(例如d/m/y)。我尝试了以下代码:</p> <pre class="brush:php;toolbar:false;">daily_max = db.func.max(db.session.query(db.func.count(Events.id),\ db.func.date_format(Events.timestamp_event,'%d/%m/%y'))\ .group_by(db.func.date_format(Events.timestamp_event,'%Y%M%D')))</pre> <p>然后希望daily_max[0]有值,daily_max[1]没有hh:mm:ss的日期。</p> <p>当我在查询后打印daily_max时,值为:</p> <pre class="brush:php;toolbar:false;">daily_max = max((SELECT count(events.id) AS count_1, date_format(events.timestamp_event, :date_format_2) AS date_format_1 FROM events GROUP BY date_format(events.timestamp_event, :date_format_3)))</pre> <p>这是数据样本。答案(<code>daily_max</code>的值)应该是<strong>(3, "21/01/2022")</strong>:</p> <pre class="brush:php;toolbar:false;">id timestamp_event ---- --------------- 1 2022-01-15 12:34 2 2022-01-21 01:23 3 2022-01-21 05:33 4 2022-01-21 11:11 5 2022-01-23 00:01 6 2022-01-23 23:29</pre> <p>对于我做错了什么有什么线索吗?在文档中找不到答案。</p>
P粉738346380
P粉738346380

全部回复(1)
P粉541565322

这是一种糟糕(低效)的方法:

daily_max = db.session.query(db.func.count(Events.id),
            db.func.date_format(Events.timestamp_event,'%d/%m/%y'))\
            .group_by(db.func.date_format(Events.timestamp_event,'%Y%M%D'))\
            .order_by(db.func.count(Events.id).desc()).first()

它将所有的(id计数,日期)对进行分组,按计数的逆序对这些对进行排序,然后获取第一个对。

它能完成工作,但我真的很想知道使用func.max()的高效、优雅的方法。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!