使用mysql中的内部联接在同一个表中添加不同的列

时间:2015-01-23 08:38:40

标签: mysql

我想报告特定项目的时间输入。我试过下面的查询。

表1:项目

id   | Name
------------
1    |  A
2    |  B

表2:EmployeeTimeEntry

proj | activity  |time
----------------------
1    | coding    | 5
2    | coding    | 2
1    | testing   | 2
1    | coding    | 2

我对项目A的期望Outpput:

proj  | TotalDur  | activity | Activitytime
--------------------------------------------
A     |  9        | coding   |  7
A     |  9        | testing  |  2

我的查询:

$query = "SELECT        
    name  as 'Proj',        
    TimeEntry.Total as 'TotalDur',
    ATimeEntry.ADetails as 'activity',
    ATimeEntry.ATotal as 'Activitytime'             
    FROM Projects pr

    INNER JOIN(SELECT project,SUM(time) as Total from EmployeeTimeEntry group by project ) TimeEntry on pr.id = TimeEntry.project
    INNER JOIN(SELECT project,details as ADetails,SUM(time) as ATotal from EmployeeTimeEntry where id = pr.id group by details ) ATimeEntry on pr.id = TimeEntry.project";

但我的输出为

proj  | TotalDur  | activity | Activitytime
--------------------------------------------
A     |  9        | coding   |  9
A     |  9        | testing  |  2

添加所有项目的所有活动时间。  我使用combobo来选择要显示报告的项目。

2 个答案:

答案 0 :(得分:1)

我认为你过度复杂了

select
p.name as Proj,
x.TotalDur,
et.activity,
sum(et.time) as Activitytime
from Projects p
join (
   select proj, sum(time) as TotalDur from EmployeeTimeEntry group by proj
)x on x.proj = p.id
join EmployeeTimeEntry et on et.proj = p.id
where p.name = 'A'
group by p.name,et.activity

<强> DEMO

答案 1 :(得分:0)

也许这就是你想要的?

select 
    p.Name as Proj, 
    (select sum(time) as TotalDur from EmployeeTimeEntry where proj = p.id group by proj) TotalDur, 
    activity, 
    sum(e.time) as ActivityTime 
from Projects p
inner join EmployeeTimeEntry e on e.proj = p.id
where p.Name = 'A'
group by name, activity, p.id

Sample SQL Fiddle