如何为sql中的每个值计算表行数?

qvsjd97n  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(423)

我是新来的,所以如果它不是固定的主题,请修复我。我有这张table:

id | uid | month | year
-----------------------
1 | 5 | 12 | 2018
2 | 5 | 12 | 2018
3 | 9 | 12 | 2018
4 | 3 | 01 | 2019

我想数一数每一次多少次 uid 这个 month 以及 year 值等于- month=12 以及 year=2018 例如,我想得到这样的回答:

uid=5 - count = 2
uid=9 - count = 1

怎么可能?

h5qlskok

h5qlskok1#

可以使用条件聚合:

select uid,
       sum(case when year = 2018 and month = 12 then 1 else 0 end) as cnt
from t
group by uid;

这将包括 uid s的计数为0。如果只需要计数大于0的uid,请使用 where 条款:

select uid, count(*)
from t
where year = 2018 and month = 12
group by uid;
ffvjumwh

ffvjumwh2#

group by uid :

select uid, count(*) as counter
from table
where month = 12 and year = 2018
group by uid
jhdbpxl9

jhdbpxl93#

从表中选择uid,count(*),其中year=2018 and month=12按uid分组

相关问题