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
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
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;
SELECT CUSTOMER, COUNT(LIKED) AS TOTAL_LIKES
FROM TABLE
WHERE LIKED = 'true'
GROUP BY CUSTOMER
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.