0

我有以下代码返回当前工作的透视表及其估计时间:

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.EstimatedTime5.30 是j.ActualTime)。

干杯

4

1 回答 1

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
于 2013-07-09T23:13:15.080 回答