簡體   English   中英

如何計算SQL中每個值的表行?

[英]How to count table rows for each value in SQL?

我是新來的,所以如果它的主題不固定,請修復我。 我有這張桌子:

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

我想計算每個uidmonthyear值等於month=12 AND year=2018

例如,我想得到這樣的響應:

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

怎么可能?

group by uid

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

您可以使用條件聚合:

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

這將包括計數為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM