[英]How to count table rows for each value in SQL?
I am new here so if its not fixed topic please fix me. 我是新来的,所以如果它的主题不固定,请修复我。 I have this table:
我有这张桌子:
id | uid | month | year
-----------------------
1 | 5 | 12 | 2018
2 | 5 | 12 | 2018
3 | 9 | 12 | 2018
4 | 3 | 01 | 2019
I want to count how much times for each uid
the month
and year
values equal to - month=12
AND year=2018
我想计算每个
uid
的month
和year
值等于month=12
AND year=2018
for example I want to get response like that: 例如,我想得到这样的响应:
uid=5 - count = 2
uid=9 - count = 1
How its possible? 怎么可能?
With group by uid
: 与
group by uid
:
select uid, count(*) as counter
from table
where month = 12 and year = 2018
group by uid
You can use conditional aggregation: 您可以使用条件聚合:
select uid,
sum(case when year = 2018 and month = 12 then 1 else 0 end) as cnt
from t
group by uid;
This will include uid
s with a count of 0. If you just want uids where the count is greater than 0, use a where
clause: 这将包括计数为0的
uid
。如果只希望计数大于0的uid,请使用where
子句:
select uid, count(*)
from t
where year = 2018 and month = 12
group by uid;
选择uid,从year = 2018和month = 12按uid分组的表中选择count(*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.