尝试这个
CREATE TABLE #Table1
([uid] int, [name] varchar(4), [diseaseid] int, [intensity] varchar(4))
;
INSERT INTO #Table1
([uid], [name], [diseaseid], [intensity])
VALUES
(1, 'xxxx', 1, 'high'),
(1, 'xxxx', 2, 'low')
;
SELECT MAX([uid]) AS [uid]
,MAX([name]) AS [name]
,MAX([diseaseid1]) AS [diseaseid1]
,MAX([intensity1]) AS [intensity1]
,MAX([diseaseid2]) AS [diseaseid2]
,MAX([intensity2]) [intensity2]
FROM
(
SELECT [uid], [name]
, CASE WHEN rn=2 THEN NULL ELSE [diseaseid] END AS [diseaseid1]
, CASE WHEN rn=2 THEN NULL ELSE [intensity] END AS [intensity1]
, CASE WHEN rn=1 THEN NULL ELSE [diseaseid] END AS [diseaseid2]
, CASE WHEN rn=1 THEN NULL ELSE [intensity] END AS [intensity2]
FROM
(
SELECT [uid], [name], [diseaseid], [intensity],
ROW_NUMBER() OVER(PARTITION BY [uid] ORDER BY Name) AS rn
FROM #Table1
) T
) T
GROUP BY [uid], [name]
DROP TABLE #Table1
EIDT
试试这个动态列
CREATE TABLE #Table1
([uid] int, [name] varchar(10), [diseaseid] int, [intensity] varchar(10))
INSERT INTO #Table1
([uid], [name], [diseaseid], [intensity])
VALUES
(1, 'xxxx', 1, 'high'),
(1, 'xxxx', 2, 'low'),
(1, 'xxxx', 3, 'medium')
DECLARE @MaxRows INT
DECLARE @CurrentRow INT
DECLARE @Query VARCHAR(MAX)
SET @CurrentRow = 1
SELECT @MaxRows = MAX(cnt) FROM (
SELECT COUNT(name) cnt FROM #Table1 GROUP BY [uid]
) AS T
SET @Query = '
SELECT MAX([uid]) AS [uid]
,MAX([name]) AS [name]'
WHILE @CurrentRow <= @MaxRows
BEGIN
SET @Query= @Query + '
,MAX(diseaseid'+CONVERT(VARCHAR(10),@CurrentRow)+') AS diseaseid'+CONVERT(VARCHAR(10),@CurrentRow)+''
SET @Query= @Query + '
,MAX(intensity'+CONVERT(VARCHAR(10),@CurrentRow)+') AS intensity'+CONVERT(VARCHAR(10),@CurrentRow)+''
SET @CurrentRow = @CurrentRow + 1
END
SET @Query= @Query + ' FROM
(
SELECT [uid], [name]'
SET @CurrentRow = 1
WHILE @CurrentRow <= @MaxRows
BEGIN
SET @Query= @Query + '
, CASE WHEN rn='+CONVERT(VARCHAR(10),@CurrentRow)+' THEN [diseaseid] ELSE NULL END AS diseaseid'+CONVERT(VARCHAR(10),@CurrentRow)+''
SET @Query= @Query + '
, CASE WHEN rn='+CONVERT(VARCHAR(10),@CurrentRow)+' THEN [intensity] ELSE NULL END AS intensity'+CONVERT(VARCHAR(10),@CurrentRow)+''
SET @CurrentRow = @CurrentRow + 1
END
SET @Query= @Query + ' FROM
(
SELECT [uid], [name], [diseaseid], [intensity],
ROW_NUMBER() OVER(PARTITION BY [uid] ORDER BY Name) AS rn
FROM #Table1
) T2
) T3
GROUP BY [uid], [name]'
PRINT (@Query)
EXEC (@Query)
DROP TABLE #Table1