Consider the query below:
SELECT DISTINCT ON (ser.id) * FROM server ser LEFT JOIN subscription sub ON ser.id = sub.server_id WHERE ( COUNT(SELECT err.id FROM error err WHERE ser.id = err.id) > 0 OR SUM(SELECT pay.amount FROM payment pay WHERE ser.id = pay.id) > 0 ); Here, a list of unique servers that are being subscribed to and that has errors or payments is returned.
However, instead of returning all server columns (*), I want to return the server id, the number of errors and the sum of payments. For example, the initial selection should look like this:
SELECT DISTINCT ON (ser.id) ser.id, countErrors, sumPayments Selecting ser.id is straight forward, but how can countErrors and sumPayments be selected from the aggregate functions "count" and "sum" (considering that they are conditions in a WHERE clause)?
I imagined the "where" conditions would look something like this:
COUNT(SELECT err.id FROM error err WHERE ser.id = err.id) AS countErrors > 0 OR SUM(SELECT pay.amount FROM payment pay WHERE ser.id = pay.id) AS sumPayments > 0 Is it possible to do this? If so, how can it be achieved?
Test data is shown below:
server +----+ | id | +----+ | 1 | +----+ | 2 | +----+ | 3 | +----+ | 4 | +----+ subscription +----+-----------+ | id | server_id | +----+-----------+ | 1 | 1 | +----+-----------+ | 2 | 2 | +----+-----------+ | 3 | 2 | +----+-----------+ | 4 | 3 | +----+-----------+ | 5 | 3 | +----+-----------+ error +----+-----------+ | id | server_id | +----+-----------+ | 1 | 1 | +----+-----------+ | 3 | 4 | +----+-----------+ payment +----+-----------+--------+ | id | server_id | amount | +----+-----------+--------+ | 1 | 1 | 200 | +----+-----------+--------+ | 2 | 2 | 200 | +----+-----------+--------+ | 3 | 2 | 100 | +----+-----------+--------+ Wanted result from test data:
+-----------+-------------+-------------+ | server_id | countErrors | sumPayments | +-----------+-------------+-------------+ | 1 | 1 | 200 | +-----------+-------------+-------------+ | 2 | 0 | 300 | +-----------+-------------+-------------+ - Server#4 has no subscription, so it should be left out.
- Server#3 has a subscription, but no errors or payments, so should be left out.
- Server#1 and server#2 both have subscription and payments and/or errors.
