在這裏,你有一個轉動的數據,你想要的方式一個示例腳本。它能做什麼:
- 創建臨時表
#t
與你給
- 確定羣ID的動態樞轉
@GroupIDCols
- 確定羣ID的在
@GroupIDSel
- 支點動態選擇的樣本數據中
#t
數據。首先將行號分配給#t
中的行以區分某個GroupID的人員(請參閱派生表t
)。然後在派生表上使用PIVOT以獲得所需的結果。
腳本:
CREATE TABLE #t(
GroupID CHAR(2),
InActive BIT,
Name VARCHAR(16)
);
INSERT INTO #t
(GroupID,InActive,Name)
VALUES
('G1',0,'Person1'),
('G2',0,'Person2'),
('G3',0,'Person1'),
('G1',1,'Person3'),
('G2',0,'Person4'),
('G4',0,'Person4');
DECLARE @GroupIDCols VARCHAR(MAX);
SET @GroupIDCols=STUFF(
(SELECT DISTINCT
','+QUOTENAME(GroupID)
FROM
#t
WHERE
InActive=0
FOR
XML PATH('')
)
,1
,1
,''
);
DECLARE @GroupIDSel VARCHAR(MAX);
SET @GroupIDSel=STUFF(
(SELECT DISTINCT
',COALESCE('+QUOTENAME(GroupID)+','''') AS '+QUOTENAME(GroupID)
FROM
#t
WHERE
InActive=0
FOR
XML PATH('')
)
,1
,1
,''
);
DECLARE @query VARCHAR(MAX);
SET @query='
SELECT
'[email protected]+'
FROM
(
SELECT
GroupID,
Name,
ROW_NUMBER() OVER (PARTITION BY GroupID ORDER BY Name) AS rn
FROM
#t
WHERE
InActive=0
) AS t
PIVOT(
MAX(Name)
FOR GroupID IN ('[email protected]+')
) AS piv
';
EXEC (@query);
DROP TABLE #t;
結果:
G1 G2 G3 G4
Person1 Person2 Person1 Person4
Person4
搜索'pivot' –