我试图从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
我的表结构是 -
JobDetails
ID - PK Auto increment
JobID - Int (Joined to Jobs table)
PhaseID - String (joined to JobPhases table)
JobPhases
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等?
干杯
答案 0 :(得分:2)
检查一下你可能会知道如何实现它
Distinct Row values as Columns 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)
答案 1 :(得分: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