0

I would like to count the aggregate function, for eg:

SELECT customer_id, SUM(amount)
FROM payment
GROUP BY customer_id
HAVING SUM(amount)>100;

So, how do I use COUNT() on SUM() to count the filtered SUM()?

1
  • 1
    Your HAVING clause is already doing this. Add sample data to your question for best results. Commented Aug 7, 2021 at 2:39

2 Answers 2

2

You wrap it in an outer query.

select count(*) from (
  SELECT customer_id, SUM(amount)
  FROM payment
  GROUP BY customer_id
  HAVING SUM(amount)>100
) big_spenders
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to count the number of customers for each amount that you get from your query, you need a 2nd level of aggregation:

SELECT amount, COUNT(*) counter
FROM (
  SELECT customer_id, SUM(amount) amount
  FROM payment
  GROUP BY customer_id
  HAVING SUM(amount)>100
) t
GROUP BY amount;

Or, with COUNT() window function:

SELECT DISTINCT SUM(amount) amount,
       COUNT(*) OVER (PARTITION BY SUM(amount)) counter
FROM payment
GROUP BY customer_id
HAVING SUM(amount)>100;

See a simplified demo.

1 Comment

Never thought of using 2nd level of aggregation. Thank you for answering and demo!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.