我有一个如下表所示的SQL表:
ID StepID Rating Comments StaffID Date
-------------------------------------------------------------
1 1 6 blah blah 1025 2014-03-20
1 2 6 blah blah 1025 2014-03-20
1 3 8 blah blah 1025 2014-03-20
1 4 7 blah blah 1025 2014-03-20
如您所见,列ID,注释,StaffID和日期的数据重复(相同)。
如何将上表变成以下内容:
ID Step1 Step2 Step3 Step4 Comments StaffID Date
----------------------------------------------------------------------------------
1 6 6 8 7 blah blah 1025 2014-03-20
任何帮助表示赞赏!
答案 0 :(得分:2)
你可以这样做:
测试数据
DECLARE @tbl TABLE(ID INT,StepID int,Rating INT,
Comments VARCHAR(200), StaffID INT,Date DATETIME)
INSERT INTO @tbl
VALUES
(1,1,6,'blah blah',1025,'2014-03-20'),
(1,2,6,'blah blah',1025,'2014-03-20'),
(1,3,8,'blah blah',1025,'2014-03-20'),
(1,4,7,'blah blah',1025,'2014-03-20')
<强>查询强>
SELECT
pvt.ID,
pvt.[1] AS Step1,
pvt.[2] AS Step2,
pvt.[3] AS Step3,
pvt.[4] AS Step4,
pvt.Comments,
pvt.StaffID,
pvt.Date
FROM
(
SELECT
*
FROM
@tbl AS tbl
) AS sourceTable
PIVOT
(
MAX(Rating)
FOR StepID IN ([1],[2],[3],[4])
) AS pvt
修改强>
如果您不知道自己有多少步骤。你需要做一个动态的支点。像这样:
测试数据
CREATE TABLE tbl
(
ID INT,
StepID int,
Rating INT,
Comments VARCHAR(200),
StaffID INT,
Date DATETIME
)
INSERT INTO tbl
VALUES
(1,1,6,'blah blah',1025,'2014-03-20'),
(1,2,6,'blah blah',1025,'2014-03-20'),
(1,3,8,'blah blah',1025,'2014-03-20'),
(1,4,7,'blah blah',1025,'2014-03-20')
获得独特的步骤:
DECLARE @cols VARCHAR(MAX)
SELECT @cols=STUFF
(
(
SELECT DISTINCT
',' +QUOTENAME('Step'+CAST(tbl.StepID AS VARCHAR(100)))
FROM
tbl
FOR XML PATH('')
)
,1,1,'')
执行动态数据透视:
DECLARE @query NVARCHAR(4000)=
'SELECT
*
FROM
(
SELECT
tbl.Comments,
tbl.Date,
tbl.ID,
tbl.Rating,
tbl.StaffID,
''Step''+CAST(tbl.StepID AS VARCHAR(100)) AS StepID
FROM
tbl
) AS sourceTable
PIVOT
(
MAX(Rating)
FOR StepID IN ('+@cols+')
) AS pvt
DROP TABLE tbl'
EXECUTE(@query)
在我的情况下放弃桌子:
DROP TABLE tbl