简体   繁体   English

MySQL - 如何从所有记录中获取特定值的计数

[英]MySQL - How to get counts of specific value from all the records

I have course table and I am storing completion status of users with 'A'. 我有课程表,我用“A”存储用户的完成状态。 Now I want to get how many A is available from CompletionStatus field for all records. 现在我想知道所有记录的CompletionStatus字段有多少A可用。

I want this result: A = 5. 我想要这个结果: A = 5。

Course Table: 课程表:

CourseRecordIdx     User    CompletionStatus 
---------------     ----    --------------------
1                   152     A___A_______________
2                   147     AA_______A__________

I have tried with char_length but getting count with underscore and I want to get only total of A : 我尝试过char_length但是用下划线计算,我想只得到A总数:

SELECT char_length(CompletionStatus) FROM `course` where CourseRecordIdx = 36

Any idea how to get result with select query? 知道如何用select查询获得结果吗?

Thanks. 谢谢。

You can use LENGTH and REPLACE for that purpose : 您可以为此目的使用LENGTHREPLACE

SELECT LENGTH(CompletionStatus) - LENGTH(REPLACE(CompletionStatus, 'A', '')) as count_Char
 FROM `course`

This basically counts how many characters are in that string, and then checks the difference between that number, and the number of characters with out the specific character. 这基本上计算该字符串中的字符数,然后检查该数字与具有特定字符的字符数之间的差异。

您可以尝试这种最简单的方法:

 SELECT length(REPLACE("field_name","_","")) FROM `tbl_name`;

I suppose the following will work, first replace all _ with '' . 我想以下内容将起作用,首先用''替换所有_ After that use char_length() function. 之后使用char_length()函数。

SELECT CHAR_LENGTH(REPLACE(CompletionStatus,'_','') as totalA FROM course where CourseRecordIdx = 36;

You can write this query for this: 您可以为此编写此查询:

SELECT CourseRecordIdx,User,CompletionStatus,
ROUND (   
    (
    LENGTH(CompletionStatus)- LENGTH( REPLACE ( CompletionStatus, "A", "")) 
    ) / LENGTH("A")) AS count    
from `course` where CourseRecordIdx = 36

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM