Home > Database > Mysql Tutorial > How Can I Simplify Aggregating Columns with Distinct Filters in PostgreSQL?

How Can I Simplify Aggregating Columns with Distinct Filters in PostgreSQL?

Linda Hamilton
Release: 2025-01-22 17:26:10
Original
950 people have browsed it

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:

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;
Copy after login

Alternative for Older PostgreSQL Versions

For versions prior to PostgreSQL 9.4, a workaround using Boolean expressions within the aggregate function is available:

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;
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template