PostgreSQL條件計數:最佳化方法
在資料庫表中統計資料出現次數時,條件語句可能會顯得冗長。幸運的是,PostgreSQL 提供了便捷且有效率的解決方案。
FILTER聚合選項
對於PostgreSQL 9.4及更高版本,利用FILTER聚合選項可獲得最佳效率:
<code class="language-sql">SELECT category , count(*) FILTER (WHERE question1 = 0) AS zero , count(*) FILTER (WHERE question1 = 1) AS one , count(*) FILTER (WHERE question1 = 2) AS two FROM reviews GROUP BY 1;</code>
簡潔的文法
如果簡潔性是您的首要任務:
<code class="language-sql">SELECT category , count(question1 = 0 OR NULL) AS zero , count(question1 = 1 OR NULL) AS one , count(question1 = 2 OR NULL) AS two FROM reviews GROUP BY 1;</code>
交叉表查詢
對於處理大型選項清單並追求更高效能,請考慮使用crosstab()函數:
<code class="language-sql">SELECT * FROM crosstab( 'SELECT category, question1, count(*) AS ct FROM reviews GROUP BY 1, 2 ORDER BY 1, 2' , 'VALUES (0), (1), (2)' ) AS ct (category text, zero int, one int, two int);</code>
以上是如何有效率地統計 PostgreSQL 中的條件出現次數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!