5

If I have a table like

customer liked
1        true
2        true
3        true
1        true
2        false

How can I count the total liked but group by customer, so I end up with something like:

customer total_likes
1        2
2        1
3        1

5 Answers 5

3

GROUP BY and a condition COUNT should do:

SELECT customer, COUNT(CASE WHEN liked = 'true' THEN 1 END) AS likes
FROM yourtable
group by customer

if it's a boolean column, do:

SELECT customer, COUNT(CASE WHEN liked THEN 1 END) AS likes
FROM yourtable
group by customer
Sign up to request clarification or add additional context in comments.

Comments

3

In Postgres, you can use the shorthand for conversion from a boolean to an integer:

select customer, sum(liked::int) as total_likes
from t
group by customer;

Note that this will return all customers, not only those with likes. If you only want customers with likes, then a where clause is appropriate:

select customer, count(*)
from t
where liked
group by customer;

Comments

2
SELECT CUSTOMER, COUNT(LIKED) AS TOTAL_LIKES
FROM TABLE
WHERE LIKED = 'true'
GROUP BY CUSTOMER

2 Comments

Thanks for this, would this allow counting against multiple columns? So if I added a third column I could get the total to include that as well? I have tried COUNT(liked AND some_other_column) which doesnt seem to affect the totals
You can use COUNT(*) , and in WHERE clause you filter the results you want
2

I assume that liked is a boolean type field,

SELECT customer, COUNT(liked) AS total_likes
FROM table_name 
WHERE liked is true
GROUP BY customer

Comments

1

Use a CASE statement inside of a COUNT function.

SELECT customer, COUNT(CASE WHEN liked = 'true' THEN 1 ELSE NULL END) AS total_likes
FROM yourtable

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.