MySQL:选择唯一名称,但总和匹配列

时间:2014-12-15 21:13:42

标签: mysql sql

我是SQL的新手,无法弄清楚如何获得我需要的东西。我正在尝试只获取Unique project_id并将所有“hours_worked”添加到每个phase_id。

这就是我想要完成的事情(见图):

project       |  phase1  |  phase 2  |  phase 5  |
"myproject1"  |    0     |     4     |    11.5   |

这可能在一个声明中吗?

enter image description here

2 个答案:

答案 0 :(得分:2)

从记忆中写作:

SELECT project_id,
sum(case when phase_id=1 then hours_worked else 0 end),
sum(case when phase_id=2 then hours_worked else 0 end),
sum(case when phase_id=5 then hours_worked else 0 end)
from table_name
group by project_id

答案 1 :(得分:0)

假设MySQL和阶段事先已知,我们可能会冒这个风险:

select project_id, 
sum(if(phase_id=1,hours_worked,0)) as phase1,
sum(if(phase_id=2,hours_worked,0)) as phase2,
sum(if(phase_id=3,hours_worked,0)) as phase3,
...
from theTableOfProjects
group by project_id;