"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can a Single SQL Query Retrieve Distinct Sums Based on Multiple WHERE Clause Conditions?

How Can a Single SQL Query Retrieve Distinct Sums Based on Multiple WHERE Clause Conditions?

Published on 2025-01-29
Browse:478

How Can a Single SQL Query Retrieve Distinct Sums Based on Multiple WHERE Clause Conditions?

Use multiple where clauses to retrieve different data

In SQL, you can use the where clause to filter a specific row to customize the method of retrieved data from the table. This problem proposes the challenge to extract two different datasets from the same table, and each data set meets different where clauses.

The sample table "TransaCTIONS" stores the records of financial transactions, which are characterized by its ID, account ID, budget ID, points and transaction types obtained. The task is to calculate the sum of the distribution accumulation of each unique budget ID and the sum of the distribution points.

For this, it can construct a single SQL query, which combines the necessary WHERE clauses. The following query achieves the result of the required:

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

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
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3