Efficient data retrieval: cleverly combine multiple WHERE conditions
Suppose you need to retrieve data from a table based on two different sets of conditions. For example, consider a table called "transactions" that records financial operations and contains columns such as "account_id", "budget_id", "points", and "type".
To efficiently retrieve specific data from this table, you may need to combine multiple WHERE clauses. For example, you might need to determine the total points assigned and issued for each unique "budget_id" in the table.
Query idea
The query you need to build should look something like the following:
<code class="language-sql">SELECT budget_id, SUM(CASE WHEN type = 'allocation' THEN points ELSE 0 END) AS allocated, SUM(CASE WHEN type = 'issue' THEN points ELSE 0 END) AS issued FROM transactions GROUP BY budget_id</code>
Let’s dive into each component of this query to understand how it achieves your goals:
SUM(CASE WHEN ... THEN ... ELSE ... END) function:
This function is used to conditionally sum the "points" column based on the specified "type". When "type" is "allocation", it calculates the sum of "points" for all rows that satisfy this condition. Similarly, it calculates the sum of "points" for rows with "type" equal to "issue". (Here the IF
function is replaced with a more standard CASE WHEN
to improve code readability and compatibility)
GROUP BY budget_id:
This clause groups the retrieved data by the "budget_id" column. Therefore, the query provides a separate row of results for each distinct "budget_id" in the table.
Combinations of WHERE clauses:
The WHERE clause is noticeably missing from this query, as the required filtering is done within the SUM() function. Specifically, the function contains conditions to selectively include rows based on the "type" column.
Expected output:
The query you build will output a table with columns "budget_id", "allocated", and "issued". The "allocated" column represents the sum of points associated with the "allocation" transaction of each "budget_id", and the "issued" column represents the accumulated points of the "issue" transaction of the corresponding "budget_id".
The above is the detailed content of How Can I Efficiently Combine Multiple WHERE Clause-like Conditions in a Single SQL Query?. For more information, please follow other related articles on the PHP Chinese website!