简体   繁体   中英

mysql: for a single column count number of rows for occurrence of specific values

I am writing a report using MySQL query. It has multiple columns that I report. Within that, there is one column containing many different values (only one value pre row). There are two specific values in that column that I need to count. The final results are then grouped by type:

Table

ID Name  has passed  Type  
 1  abc      yes (1)   z  
 2  xyz      yes (1)   x  
 3  cde      no  (0)   y  
 4  abc      yes (1)   z  
 5  cde      no  (0)   z  
 6  xyz      no  (0)   y  

My expected result is:

For Type x  
 total records = 1  
 yes count = 1     
 total abc = 0  
 total cde = 0  

For Type y  
 total records = 2  
 yes count = 0     
 total abc = 0  
 total cde = 1  

For Type z  
 total records = 3  
 yes count = 2   
 total abc = 2  
 total cde = 1  

Notice that we don't count name xyz or any other name.

SELECT
    type,
    COUNT(*) AS total_records,
    COUNT(IF(has_passed, 1, NULL)) AS yes_count,
    COUNT(IF(name = 'abc', 1, NULL)) AS total_abc,
    COUNT(IF(name = 'cde', 1, NULL)) AS total_cde
FROM
    table
GROUP BY
    type

Off the top of my head (don't have access to a database for testing right now, sorry)... Maybe something like this would work (assuming you're storing 0 and 1 for "passed")?

SELECT
   type,
   SUM(passed) as "Yes count",
   SUM(case when name = 'abc' then 1 else 0 end) as "Total abc",
   SUM(case when name = 'cde' then 1 else 0 end) as "Total cde",
   COUNT(1) as "Total records"
FROM
   myTable
GROUP BY
   type
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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