CREATE VIEW A1 AS
SELECT client_ID , COUNT(dog_id)
FROM test_clients
GROUP BY client_ID
HAVING COUNT(dog_id)=2;
CREATE VIEW A2 AS
SELECT filial , COUNT(A1.client_ID)
FROM A1
JOIN test_clients USING (client_ID)
GROUP BY filial
HAVING COUNT(A1.client_ID)>10;
SELECT COUNT(filial)
FROM A2;
As far as I understand, this can be done through a subquery, but how?
2
Answers
Burns down to:
Assuming
filial
is definedNOT NULL
.Probably faster to use a window function and get rid of the self-join:
Depending on your exact table definition we might be able to optimize a bit further …
A slight refractor of Erwin’s suggestion, just for you to play around with…
The outer query works because…
COUNT() OVER ()
)You may or may not want the
COUNT(DISTINCT client_id)
, its not clear. So, play with that too.I’m not saying it’s any better, just that it’s different and might help your learning.