Home >Database >Mysql Tutorial >How Can I Simplify Aggregating Columns with Distinct Filters in PostgreSQL?
Streamlining Column Aggregation with Distinct Filters in PostgreSQL
The following code aggregates data from multiple tables, applying distinct filters to categorize played, won, and lost games. While functional, its complexity and length warrant a more efficient approach. This article explores simpler methods.
Leveraging the FILTER
Clause (PostgreSQL 9.4 and later)
PostgreSQL 9.4 and subsequent versions offer the standard SQL FILTER
clause, enabling dynamic filtering within aggregations. This significantly simplifies the query:
<code class="language-sql">SELECT u.name, COUNT(*) FILTER (WHERE g.winner_id > 0) AS played, COUNT(*) FILTER (WHERE g.winner_id = u.id) AS won, COUNT(*) FILTER (WHERE g.winner_id <> u.id) AS lost FROM games g JOIN users u ON u.id IN (g.player_1_id, g.player_2_id) GROUP BY u.name;</code>
Alternative for Older PostgreSQL Versions
For versions prior to PostgreSQL 9.4, a workaround using Boolean expressions within the aggregate function is available:
<code class="language-sql">SELECT u.name, COUNT(g.winner_id > 0 OR NULL) AS played, COUNT(g.winner_id = u.id OR NULL) AS won, COUNT(g.winner_id <> u.id OR NULL) AS lost FROM games g JOIN users u ON u.id IN (g.player_1_id, g.player_2_id) GROUP BY u.name;</code>
This method, while less efficient than the FILTER
clause, offers a practical solution for older PostgreSQL installations.
Summary
Employing the FILTER
clause (PostgreSQL 9.4 ) or the Boolean workaround provides a more concise and, in most cases, performant solution. The FILTER
clause is the preferred approach for newer versions due to its improved readability and efficiency. For older versions, the Boolean workaround remains a viable alternative.
The above is the detailed content of How Can I Simplify Aggregating Columns with Distinct Filters in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!