PostgreSQL:以分鐘計算查詢結果的行數
本文介紹如何在PostgreSQL中使用視窗函數按分鐘計算查詢結果的運行行數。
一、每分鐘的行數
以下查詢傳回每分鐘的行數:
<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_count FROM mytable ORDER BY minute;</code>
說明:
date_trunc('minute', "when")
將時間戳列 "when" 截斷到最近的分鐘。 COUNT(*) OVER (ORDER BY date_trunc('minute', "when"))
計算每分鐘的運行行數。 ORDER BY
子句指定聚合的行的排序。 DISTINCT
用於確保只回傳唯一的分鐘。這是因為 COUNT
聚合函數將為同一分鐘傳回多行。 三、包含無活動的分鐘
如果要包含結果中無活動的分鐘,可以使用以下查詢:
<code class="language-sql">SELECT m.minute, COALESCE(SUM(c.minute_count) OVER (ORDER BY m.minute), 0) AS running_count FROM ( SELECT generate_series(MIN(minute), MAX(minute), INTERVAL '1 minute') AS minute FROM ( SELECT date_trunc('minute', "when") AS minute, COUNT(*) AS minute_count FROM mytable GROUP BY minute ) AS sub ) AS m LEFT JOIN ( SELECT date_trunc('minute', "when") AS minute, COUNT(*) AS minute_count FROM mytable GROUP BY minute ) AS c ON m.minute = c.minute ORDER BY m.minute;</code>
說明:
LEFT JOIN
來包含無活動的分鐘。 generate_series()
函數產生表中最小分鐘和最大分鐘之間的一系列分鐘。 COALESCE()
函數確保無活動的分鐘的運行計數為 0。 以上是如何在 PostgreSQL 中計算每分鐘運行行數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!