高效計算 SQL 中的條件出現次數
本指南探討了計算 SQL 查詢中條件資料出現次數的各種方法,並按特定列分組。最佳方法取決於您的資料庫系統。
PostgreSQL 9.4 及更高版本:FILTER
子句
PostgreSQL 9.4 及後續版本使用 FILTER
聚合函數中的 COUNT
子句提供了最高效且可讀的解決方案:
<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 category;</code>
PostgreSQL 的簡潔替代方案
更短的語法實現相同的結果:
<code class="language-sql">SELECT category, COUNT(CASE WHEN question1 = 0 THEN 1 END) AS zero, COUNT(CASE WHEN question1 = 1 THEN 1 END) AS one, COUNT(CASE WHEN question1 = 2 THEN 1 END) AS two FROM reviews GROUP BY category;</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); ``` This approach dynamically handles a larger number of categories more efficiently than the previous methods.</code>
以上是如何有效率地統計 SQL 查詢中的條件出現次數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!