0

我试图从 SQL 2008 查询中生成以下输出 -

JobID | Repair & Reshape | Refit Stripped Parts | Polishing 
1000  | true             | true                 | false
1001  | true             | true                 | false
1002  | true             | true                 | false
1003  | true             | true                 | false
1004  | true             | true                 | false

我拥有的表结构是 -

工作详情

ID - PK Auto increment
JobID - Int (Joined to Jobs table)
PhaseID - String (joined to JobPhases table)

工作阶段

ID - PK String
Name - VarChar(150)

到目前为止,我有 -

SELECT JobID, [0], [1], [2], [3], [4], [5], [6], [7]
 FROM    
(   
    SELECT  JobID, PhaseID, [x] = 1 FROM    JobDetails  
) JobDetails
PIVOT
(   SUM(x)
    FOR PhaseID IN ([0], [1], [2], [3], [4], [5], [6], [7])
) pvt

但不确定如何用作业阶段名称替换 0-7 等?

干杯

4

2 回答 2

2

检查这个你可能会知道如何实现它

不同的行值作为列 Sql Server

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

    select @cols = STUFF((SELECT ',' + QUOTENAME(jobtype) 
                        from yourtable
                        group by jobtype
                        ORDER BY jobtype
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    --SELECT @cols
    set @query = 'SELECT  JobID,' + @cols + ' from 
                 (
                    select JobID, jobtype, jobvalue from yourtable
                ) x
                pivot 
                (
                    MAX(jobvalue)
                    for jobtype in (' + @cols + ')
                ) p '

    execute(@query)
于 2013-07-08T09:36:31.840 回答
1

JOIN该表与JobPhases锚查询中的表,然后使用阶段名称列表FOR Name IN并列出阶段名称:

SELECT *
 FROM    
(   
    SELECT  j.JobID, j.PhaseID, p.Name, x
    FROM    JobDetails  AS j
    INNER JOIN JobPhases AS p ON p.ID = j.haseId
) JobDetails
PIVOT
(   SUM(x)
    FOR Name IN ([phasename1], [phasename2], ...)
) pvt
于 2013-07-08T09:28:50.533 回答