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

时间:2017-01-30 11:39:44

标签: sql postgresql

如果我有一张像

这样的表格
recognizer.setKeywordThreshold(1e-40f)

我如何计算总体喜欢但按客户分组,所以我最终得到的结果如下:

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

5 个答案:

答案 0 :(得分:2)

GROUP BY和条件COUNT应该:

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

如果它是布尔列,请执行:

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

答案 1 :(得分:2)

在Postgres中,您可以使用简写从布尔值转换为整数:

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

请注意,这将返回所有客户,而不仅仅是那些喜欢的客户。如果您只想要喜欢的客户,那么where子句是合适的:

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

答案 2 :(得分:1)

ng-class="{className:[condition]}"

ng-class="{custom-directive:[value =='ABC']}"

答案 3 :(得分:1)

我假设SELECT customer, COUNT(liked) AS total_likes FROM table_name WHERE liked is true GROUP BY customer 是一个布尔类型字段,

ids = @anonymous.ids
ids.concat(@amitian.ids) if amitian_signed_in?
@confessions = Confession.where(amitian_id: ids).order('created_at DESC')

答案 4 :(得分:0)

CASE函数中使用COUNT语句。

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