如果你有狀態的固定數量的,你知道的狀態值,那麼你可以得到你使用下面的代碼後是什麼。
CREATE TABLE #Register(PersonID int, RegisterID int, Stat varchar)
INSERT INTO #Register (PersonID,RegisterID,Stat) VALUES
('3049518','14467','A'),
('3049518','14467','B'),
('3049518','14467','C'),
('3049518','32445','A'),
('3049518','32445','B'),
('3049518','32445','C')
SELECT PersonID
,RegisterID
,MAX(A) 'A'
,MAX(B) 'B'
,MAX(C) 'C'
FROM (
SELECT PersonID
,RegisterID
,CAST(CASE
WHEN r.stat = 'A'
THEN 'A'
ELSE NULL
END AS VARCHAR) AS 'A'
,CAST(CASE
WHEN r.stat = 'B'
THEN 'B'
ELSE NULL
END AS VARCHAR) AS 'B'
,CAST(CASE
WHEN r.stat = 'C'
THEN 'C'
ELSE NULL
END AS VARCHAR) AS 'C'
FROM #Register r
GROUP BY PersonID
,RegisterID
,Stat
) q
GROUP BY q.PersonID
,q.RegisterID
該代碼假定每個人每個狀態有一條記錄。
它輸出
如果狀態值是不固定的,你不知道它們是什麼,你可以使用下面的SQL Server:
CREATE TABLE #Register(PersonID int, RegisterID int, Stat varchar)
INSERT INTO #Register (PersonID,RegisterID,Stat) VALUES
('3049518','14467','A'),
('3049518','14467','B'),
('3049518','14467','C'),
('3049518','32445','A'),
('3049518','32445','B'),
('3049518','32445','C')
DECLARE @queryPart1 NVARCHAR(MAX)
,@queryPart2 NVARCHAR(MAX)
,@colHeader NVARCHAR(MAX)
,@query NVARCHAR(MAX)
SET @queryPart1 = 'SELECT PersonID,RegisterID'
SET @queryPart2 = 'FROM (SELECT PersonID,RegisterID'
SET @query = ''
DECLARE Stat_Cursor CURSOR
FOR
SELECT DISTINCT (STAT)
FROM #Register r
OPEN Stat_Cursor;
FETCH NEXT
FROM Stat_Cursor
INTO @colHeader
WHILE @@FETCH_STATUS = 0
BEGIN
SET @queryPart1 = @queryPart1 + ',MAX(''' + @colHeader + ''') ''' + @colHeader + ''''
SET @queryPart2 = @queryPart2 + ',CAST(CASE WHEN r.stat = ''' + @colHeader + ''' THEN ''' + @colHeader + ''' ELSE NULL END AS VARCHAR) AS ''' + @colHeader + ''''
FETCH NEXT
FROM Stat_Cursor
INTO @colHeader
END;
CLOSE Stat_Cursor;
DEALLOCATE Stat_Cursor;
SET @query = @queryPart1 + @queryPart2 + 'FROM #Register r GROUP BY PersonID ,RegisterID,Stat) q'
PRINT @query
GO
是在值列表中的'Status'列預先確定不變的,或者是完全動態的?這將顯着改變答案的複雜性。 –
您正在使用哪些DBMS? Postgres的?甲骨文? –
你怎麼知道哪個狀態是1,2或3?如果有第四種狀態呢? –