如何将多行添加到一行中?我正在尝试添加两行数据,并将数据输出到一行中以用于一个特定作业。我已经将输出减少到一个作业,但是一旦我弄清楚如何将两行合并为一个,我将在输出中放置多个作业。每个工作都有两名员工,所以我必须将两个员工加在一起,每个工作总共工作一小时。
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
*/
答案 0 :(得分: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
答案 1 :(得分:0)
一个选项是使用CTE ..因为我们不知道您的数据以及组中的哪个列导致了多列
;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