2012-02-02 16 views
0

我有两个MySQL表:MySQL的:基于字段名称count行(部分2)

缺陷

df_id | project_id | resp_id | status 
------+------------+---------+---------- 
1  |  1  | 1 | Open 
2  |  1  | 1 | Open 
3  |  1  | 1 | Closed 
4  |  1  | 2 | Open 
5  |  1  | 2 | Closed 

负责

resp_id | resp_comp_name 
--------+---------------- 
    1 |  Google 
    2 |  Firefox 

,我需要输出

resp_comp_name | open | closed 
---------------+------+-------- 
    Google  | 3 | 1 
    Firefox  | 1 | 1 

我写道:

 SELECT r.resp_comp_name, d.status, COUNT(d.df_id) AS total 
     FROM pms_defects d 
    LEFT JOIN pms_responsibles r ON d.resp_id=r.resp_id 
     WHERE d.project_id='1' AND d.resp_id != 0 
    GROUP BY d.resp_id 
    ORDER BY total DESC 

它产生:从行向

enter image description here

+1

这是一个好故事。你想让我们做什么? – 2012-02-02 11:27:58

回答

0
SELECT r.resp_comp_name, sum(if(d.status = 'Open',1,0)) as open, 
sum(if(d.status ='Closed',1,0)) as closed from pms_defects d, pms_responsibles r 
where r.resp_id = d.resp_id group by d.resp_id 

这使用if语句与和移动打开/关闭,以基于列的。