Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

mysql - How to count a filed with specific condition?

date train condition1 condition2
1 train1 0 false
2 train2 1 true
1 train3 1 true
1 train4 5 false
question from:https://stackoverflow.com/questions/65890031/how-to-count-a-filed-with-specific-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just conditional aggregation:

select date, count(*) as cnt_train,
       sum(condition1 > 0) as cnt_condition1,
       sum(condition2) as cnt_condition2
from t
group by date;

EDIT:

This uses the MySQL extension that treats boolean values as numbers in a number context, with 1 for true and 0 for false. This works for any boolean expression, so you can use more complex ones, such as:

       sum(condition1 > 0 and condition2) as cnt_condition1_and_condition2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...