查询每月返回项目小时数

时间:2013-01-29 21:43:02

标签: sql sql-server

我正在尝试创建SQL Query以在一个项目下显示任务以及每月在每个任务上花费多少小时?enter image description here

查询

SELECT 
  Projects.projectName, Tasks.taskName, 
  billingsTimes.taskID, billingsTimes.actualTotalTime
FROM Projects 
INNER JOIN Projects_tasks ON Projects.projectID = Projects_tasks.projectID 
INNER JOIN Tasks ON Projects_tasks.taskID = Tasks.taskID 
INNER JOIN billingsTimes ON Tasks.taskID = billingsTimes.taskID
WHERE (Projects.projectID = '') 

1 个答案:

答案 0 :(得分:3)

听起来你只需要以下内容:

select p.projectname,
    t.taskname,
    bt.taskid,
    bt.TotalTime
from projects p
left join projects_tasks pt
    on p.projectid = pt.projectid
left join tasks t
    on pt.taskid = t.taskid
left join
(
    select SUM(bt.actualTotalTime) TotalTime, bt.taskid
    from billingtimes bt
    group by bt.taskid
) bt
    on t.taskid = bt.taskid

如果您提供有关每月日期存储位置的更多详细信息,则可以将其更改为按月分组,以便为​​每个任务提供每月总计。

编辑#1,如果您使用dateOfService确定服务的执行时间,并且您希望按月/年分组,则可以使用以下内容:

select p.projectname,
    t.taskname,
    bt.taskid,
    bt.TotalTime,
    bt.ServiceMonth,
    bt.ServiceYear
from projects p
left join projects_tasks pt
    on p.projectid = pt.projectid
left join tasks t
    on pt.taskid = t.taskid
left join
(
    select SUM(bt.actualTotalTime) TotalTime, bt.taskid, 
        datepart(month, bt.dateofService) ServiceMonth,
        datepart(year, bt.dateofService) ServiceYear
    from billingtimes bt
    group by bt.taskid, datepart(month, bt.dateofService), 
        datepart(year, bt.dateofService)
) bt
    on t.taskid = bt.taskid