首頁  >  問答  >  主體

SQLAlchemy: 取得分組值的最大值

<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粉738346380P粉738346380415 天前434

全部回覆(1)我來回復

  • P粉541565322

    P粉5415653222023-09-02 00:35:55

    這是一種糟糕(低效率)的方法:

    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()的高效、優雅的方法。

    回覆
    0
  • 取消回覆