PIVOT中使用MAX的SQL SUM

时间:2013-07-29 10:17:56

标签: sql sql-server sql-server-2008 pivot-table

我想在我的PIVOT表中获得2个或更多TIME字段的SUM,但是因为SUM不能用于字符(转换后我可以显示EstimatedTime / ActualTime),所以我遇到了困难。

以下代码 -

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + ID + ',' + QUOTENAME(Name)
                  FROM JobPhases
                  FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)') 
                    , 1, 1, '');

SELECT @query = 'SELECT * FROM    
(   
    SELECT j.JobID, c.Registration as ''Reg.'', p.Name, 
    CAST(MAX(j.EstimatedTime) as VARCHAR(MAX)) + ''/'' +
    CAST(MAX(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, j.JobID
) JobDetails
PIVOT
(   MAX(x)
    FOR Name IN (' + @cols + ')
) pvt'

execute(@query);

生成 -

JobID | Reg.     | P13$ | Repair and Reshape                | P15$ | Refit Stripped Parts
1065  | BJ11 2VT | NULL | 01:00:00.0000000/01:54:10.5387526 | NULL | NULL

表 -

**JobDetails**
ID - PK Auto increment
JobID - Int (Joined to Jobs table)
PhaseID - String (joined to JobPhases table)
EstimatedTime - time(7)
ActualTime time(7)

**JobPhases****
ID - PK String
Name - VarChar(150)

此示例中的问题是JobID 1065有2个JobDetails -

ID | JobID | PhaseID | EstimatedTime    | ActualTime 
25 | 1065  | P13$    | 01:00:00.0000000 | 01:54:10.5387526
26 | 1065  | P13$    | 00:30:00.0000000 | 00:00:00.0000000

所以,正确的结果应该是(注意修复和重塑中的1:30) -

JobID | Reg.     | P13$ | Repair and Reshape                | P15$ | Refit Stripped Parts
1065  | BJ11 2VT | NULL | 01:30:00.0000000/01:54:10.5387526 | NULL | NULL

如何获得每个阶段ID的所有行的总EstimatedTime?

谢谢!

1 个答案:

答案 0 :(得分:1)

总结TIME列不是直截了当的,你需要的是重写你的行;

CAST(MAX(j.EstimatedTime) as VARCHAR(MAX)) + ''/'' +

类似(未经测试的)

CAST(CAST(DATEADD(ms, SUM(DATEDIFF(ms, '0:00:00', j.EstimatedTime)), 
                 '00:00:00') AS TIME) AS VARCHAR(MAX)) + ''/'' +