2016-12-13 42 views
0

如何将多行添加到总行中?我正在尝试添加两行数据,并将数据输出到一行中执行一项特定作业。我将输出裁减到了一项工作,但是一旦我弄清楚如何将两行合并为一行,我将在输出中放置多个工作。每个工作都有两名员工,所以我将不得不将两个员工的小时数加起来,以计算每个工作的总小时数。如何将总共多行添加到一行中

SELECT 
    TJ.intJobID 
    ,TJ.strJobDescription 
    ,TJS.strJobStatus 
    ,SUM(TJE.intHoursWorked) AS intTotalHoursWorked 

FROM 
    TJobs   AS TJ 
    ,TJobStatus  AS TJS 
    ,TJobEmployees AS TJE 
    ,TEmployees  AS TE 
WHERE 
    TJ.intJobID   =  TJE.intJobID 
AND TJ.intJobStatusID =  TJS.intJobStatusID 
AND TE.intEmployeeID =  TJE.intEmployeeID 
AND TJ.intJobID = 1 
GROUP BY 
    TJ.intJobID 
    ,TJE.intEmployeeID 
    ,TJ.strJobDescription 
    ,TJS.strJobStatus 
    ,TJE.intHoursWorked 


/* 

    Output I'm Getting 

    intJobID strJobStatus intTotalHoursWorked 
     1   Complete    50 
     1   Complete    42 

    Wanted Output 

    intJobID strJobStatus intTotalHoursWorked 
     1   Complete    92 

*/ 
+1

推广使用显式的' JOIN' sintaxis,Aaron Bertrand写了一篇不错的文章[踢坏坏习惯:使用旧式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick -using-old-style-joins.aspx)。 –

回答

2
SELECT 
    TJ.intJobID 
    ,TJS.strJobStatus 
    ,SUM(TJE.intHoursWorked) AS intTotalHoursWorked 

... 
... 
GROUP BY 
    TJ.intJobID 
    ,TJS.strJobStatus 

我仔细检查您的查询,你有太多的表。因为你并不真正需要TEmployees

SELECT 
    TJ.intJobID 
    ,TJ.strJobDescription 
    ,TJS.strJobStatus 
    ,SUM(TJE.intHoursWorked) AS intTotalHoursWorked 

FROM TJobs   AS TJ 
JOIN TJobStatus  AS TJS 
    ON TJ.intJobStatusID = TJS.intJobStatusID 
JOIN TJobEmployees AS TJE 
    ON TJ.intJobID  = TJE.intJobID 
GROUP BY 
    TJ.intJobID 
    ,TJS.strJobStatus 
0

一种选择是使用CTE..since我们不知道你的数据和分组哪一列所致多发性列

;with cte 
as 
(
SELECT 
    TJ.intJobID 
    ,TJ.strJobDescription 
    ,TJS.strJobStatus 
    ,SUM(TJE.intHoursWorked) AS intTotalHoursWorked 

FROM 
    TJobs   AS TJ 
    ,TJobStatus  AS TJS 
    ,TJobEmployees AS TJE 
    ,TEmployees  AS TE 
WHERE 
    TJ.intJobID   =  TJE.intJobID 
AND TJ.intJobStatusID =  TJS.intJobStatusID 
AND TE.intEmployeeID =  TJE.intEmployeeID 
AND TJ.intJobID = 1 
GROUP BY 
    TJ.intJobID 
    ,TJE.intEmployeeID 
    ,TJ.strJobDescription 
    ,TJS.strJobStatus 
    ,TJE.intHoursWorked 
) 
select 
intJobID, 
max(strJobStatus) as 'strJobStatus', 
sum(intTotalHoursWorked) as 'intTotalHoursWorked' 
from cte