我有以下代码返回当前作业及其估计时间的数据透视表:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(Name)
FROM JobPhases
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @query = 'SELECT *
FROM
(
SELECT c.Registration as ''Reg.'', p.Name, [x] = j.EstimatedTime
FROM JobDetails AS j
INNER JOIN JobPhases p ON p.ID = j.PhaseId
INNER JOIN Jobs job on job.ID = j.JobID
INNER JOIN Cars c on job.CarID = c.ID
WHERE job.Status = 1 or job.Status = 0
) JobDetails
PIVOT
( SUM(x)
FOR Name IN (' + @cols + ')
) pvt'
execute(@query);
输出:
JobID | Repair & Reshape | Refit Stripped Parts | Polishing
1000 | 2.00 | 1.00 | 1.30
1001 | 2.30 | 0.30 | 2.00
我需要的是在显示的值中连接j.ActualTime
。我有什么想法可以做到这一点?因此,最终输出为- 4.00 / 5.30
(其中4.00为j.EstimatedTime
,5.30为j.ActualTime
)。
干杯
答案 0 :(得分:1)
我会先在PIVOT之外进行所有处理。这样您就可以进行聚合,连接以及任何您想要的操作。完成所有处理后,再进行一个简单的非聚合支点:
SELECT *
FROM
(
SELECT c.Registration as ''Reg.'', p.Name,
CAST(SUM(j.EstimatedTime) as VARCHAR(MAX)) + '/' +
CAST(SUM(j.ActualTime) as VARCHAR(MAX)) as [x]
FROM JobDetails AS j
INNER JOIN JobPhases p ON p.ID = j.PhaseId
INNER JOIN Jobs job on job.ID = j.JobID
INNER JOIN Cars c on job.CarID = c.ID
WHERE job.Status = 1 or job.Status = 0
GROUP BY c.Registration, p.Name
) JobDetails
PIVOT
( MAX(x)
FOR Name IN (' + @cols + ')
) pvt