高效統計PostgreSQL分組資料中的出現次數
PostgreSQL提供了多種方法來統計分組表中資料的出現次數。例如,可以使用CASE WHEN語句來統計特定值:
<code class="language-sql">SELECT sum(CASE WHEN question1 = 0 THEN 1 ELSE 0 END) AS ZERO, sum(CASE WHEN question1 = 1 THEN 1 ELSE 0 END) AS ONE, sum(CASE WHEN question1 = 2 THEN 1 ELSE 0 END) AS TWO, category FROM reviews GROUP BY category</code>
然而,當可能的值數量增加時,使用CASE WHEN語句會變得越來越繁瑣。在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提供了多種方法進行條件SQL計數。 FILTER選項提供了一種簡潔高效的解決方案,而crosstab()
函數則為處理大量的選項提供了最佳性能。
以上是如何使用 PostgreSQL 最佳地統計分組資料中的出現次數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!