简体   繁体   English

Postgres得到计数但是由另一列分组

[英]Postgres get count but group by another column

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: GROUP BY和条件COUNT应该:

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: 在Postgres中,您可以使用简写从布尔值转换为整数:

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: 如果您只想要喜欢的客户,那么where子句是合适的:

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, 我假设liked是一个布尔类型字段,

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. COUNT函数内使用CASE语句。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM