如何将列转换为行?

时间:2015-12-22 21:44:09

标签: sql sql-server

我有下表。 COLUMN_NAME和DATA_TYPE是列名,下面是值。

SELECT SALESPERSONID
FROM SALES
GROUP BY SALESPERSONID
HAVING COUNT(*) >= 3

我想将该表转换为下表:

COLUMN_NAME      DATA_TYPE
employee_id      int
employee_name    varchar
employee_age     int

1 个答案:

答案 0 :(得分:3)

使用透视:

declare @t table(COLUMN_NAME varchar(max), DATA_TYPE varchar(max))
insert into @t values
('employee_id',      'int'),
('employee_name',    'varchar'),
('employee_age',     'int')

select * from @t
pivot(max(DATA_TYPE) for COLUMN_NAME in([employee_id],[employee_name],[employee_age]))p

输出:

employee_id employee_name   employee_age
int         varchar         int