mysql:用于单个列计数的行数,用于出现特定值

时间:2012-06-15 21:31:53

标签: mysql select

我正在使用MySQL查询编写报告。它有多个我报告的列。在其中,有一列包含许多不同的值(前一行只有一个值)。我需要计算该列中的两个特定值。然后按类型对最终结果进行分组:

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  

我的预期结果是:

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  

请注意,我们不计算名称xyz或任何其他名称。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

脱离我的头脑(现在无法访问数据库进行测试,抱歉)......也许这样的事情会起作用(假设你为“传递”存储0和1)?

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
;