TSQL Pivot Transformation行字段 - >柱

时间:2011-07-28 06:22:54

标签: sql-server tsql row pivot

我们说我有以下数据:

ID         Key        String        Number

1          Name       A             -1
1          Age        ''            30  
1          Sex        Male          -1
2          Name       B             -1 
2          Age        ''            20
2          Sex        Female        -1  

我想知道我们是否可以使用Pivot生成以下数据

ID          Name        Age           Sex
1           A           30            Male
2           B           20            Female

任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:1)

DECLARE @dat TABLE  (
id int,
name varchar(50),
string varchar(50),
number int
)

DECLARE @dat2 TABLE  (
id int,
name_col varchar(50),
val varchar(50)
)

INSERT INTO @dat (id, name, string, number) VALUES (1,'Name', 'A', -1)
INSERT INTO @dat (id, name, string, number) VALUES (1,'Age', '', 30)
INSERT INTO @dat (id, name, string, number) VALUES (1,'Sex', 'Male', -1)
INSERT INTO @dat (id, name, string, number) VALUES (2,'Name', 'A', -1)
INSERT INTO @dat (id, name, string, number) VALUES (2,'Age', '', 20)
INSERT INTO @dat (id, name, string, number) VALUES (2,'Sex', 'Female', -1)

INSERT INTO @dat2
SELECT [id], [name], [val] = CASE  WHEN number = -1 THEN string ELSE
CONVERT(varchar,number) END FROM @dat

SELECT * FROM @dat2
PIVOT
(
  MAX(val)
  FOR [name_col] IN ([Name],[Age],[Sex])
)
AS p

你会得到你期望的东西:

1   A   30  Male
2   A   20  Female

答案 1 :(得分:1)

可能更容易做到这一点?

SELECT id
,MAX(CASE WHEN Key = 'Name' THEN string END) as name
,MAX(CASE WHEN Key = 'Age' THEN number END) as age
,MAX(CASE WHEN Key = 'sex' THEN string END) as sex
FROM table
GROUP BY id