Filter search for only ID’s that have more than one POSTGRESQL linked record

Asked

Viewed 35 times

1

In the query below I can find the largest reduced linked to account, but I need it to be only in the id’s that have more than one reduced linked. The table has more than 4000 reduced

SELECT (id,
        MAX(reduzido))
FROM contas
INNER JOIN reduzidocontas ON contas.id = reduzidocontas.idconta
AND reduzidocontas.ano = 2020
GROUP BY contas.id;

example:

id | ano  | reduzido
85 | 2020 | 4745
**85 | 2020 | 43737**
**87 | 2020 | 44215**
**88 | 2020 | 1321**
**89 | 2020 | 32158*

I want to search only when you have more than one reduced linked to the ID, as in the 85 and not return when you have only one reduced as the 87, 88 and 89.

1 answer

0


Try

SELECT (id,
        MAX(reduzido))
FROM contas
INNER JOIN reduzidocontas ON contas.id = reduzidocontas.idconta
AND reduzidocontas.ano = 2020
GROUP BY contas.id
HAVING COUNT(DISTINCT reduzido) > 1

Not if postgresql accepts a having that is not in select , but puts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.