2013-07-09 71 views
0

我有下面的代碼返回當前的工作和他們的estiamted時代的樞軸表:連接一樞軸表輸出

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)。

乾杯

回答

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 
+0

這看起來像它可以工作,但我得到的錯誤「操作數的數據類型爲varchar(max)是爲運營商和無效的。」顯然這與第5行和第6行有關,不能將總和轉換爲varchar,但我無法找到解決方案?乾杯 – dynamicuser

+0

@MattBaughan我的不好。 SUM不適用於字符類型,但MAX應該。讓我知道這是否適合你。 –