2016-12-13 54 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