0

我正在使用 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 或任何其他名称。

4

2 回答 2

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
于 2012-06-15T21:42:19.933 回答
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
;
于 2012-06-15T21:44:06.020 回答