1

I have written some query and I wanted to know the number of rows or total rows count. Is there a "count" function that can be applied on top of the query?

My query is like:

select customer_id, sum(amount)
from payment
group by customer_id having sum(amount)>100; 

2 Answers 2

1

You could use count() as a window function, like in

SELECT *,
       count(*) OVER () AS total_count
FROM (SELECT customer_id,
             sum(amount)
      FROM payment
      GROUP BY customer_id HAVING sum(amount)>100) AS q;

That will return the total count in an additional column.

Sign up to request clarification or add additional context in comments.

2 Comments

There is no need for the subquery. COUNT() can be used as the 3d column in the main query.
@forpas I am trying to show a general principle. You are right in this case, but if the query contains LIMIT or OFFSET, a subquery would be necessary.
1

You can use a subquery or CTE:

select count(*)
from (select customer_id, sum(amount)
      from payment
      group by customer_id
      having sum(amount)>100
     ) c;

Comments

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.