<code class="language-sql">SELECT COUNT(id) AS count, EXTRACT(hour FROM "when") AS hour, EXTRACT(minute FROM "when") AS minute FROM mytable GROUP BY hour, minute;</code>
此查詢計算每分鐘的行數,但不提供運行總數。
方法一:只回傳有活動記錄的分鐘
<code class="language-sql">SELECT DISTINCT date_trunc('minute', "when") AS minute, count(*) OVER (ORDER BY date_trunc('minute', "when")) AS running_ct FROM mytable ORDER BY 1;</code>
此查詢使用date_trunc()
函數,傳回每個活動分鐘的行計數。它使用帶有ORDER BY
子句的視窗函數計算運行總數。
方法二:使用有連接的子查詢
<code class="language-sql">SELECT minute, sum(minute_ct) OVER (ORDER BY minute) AS running_ct FROM ( SELECT date_trunc('minute', "when") AS minute, count(*) AS minute_ct FROM tbl GROUP BY 1 ) sub ORDER BY 1;</code>
此方法在一個子查詢中聚合每分鐘的行計數。然後,主查詢連接它以累積計數,並包含沒有活動的分鐘。
方法三:使用CTE(最快)
<code class="language-sql">WITH cte AS ( SELECT date_trunc('minute', "when") AS minute, count(*) AS minute_ct FROM tbl GROUP BY 1 ) SELECT m.minute, COALESCE(sum(cte.minute_ct) OVER (ORDER BY m.minute), 0) AS running_ct FROM ( SELECT generate_series(min(minute), max(minute), interval '1 min') FROM cte ) m(minute) LEFT JOIN cte USING (minute) ORDER BY 1;</code>
此方法結合了CTE、子查詢和左連接。對於具有“when”索引的大型資料集,這是一種有效的方法。
以上是如何有效率地計算 PostgreSQL 每分鐘運行行數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!