高效计算 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中文网其他相关文章!