Marc
Marc

Reputation: 9527

How to transpose columns to rows?

I have the following table. COLUMN_NAME and DATA_TYPE are the column names and below are the values.

COLUMN_NAME      DATA_TYPE
employee_id      int
employee_name    varchar
employee_age     int

I would like to transform that table to the following table:

COLUMN_HEADER_1    COLUMN_HEADER_2    COLUMN_HEADER_3
employee_id        employee_name      employee_age
int                varchar            int

Upvotes: 0

Views: 49

Answers (1)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

With pivoting:

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

Output:

employee_id employee_name   employee_age
int         varchar         int

Upvotes: 3

Related Questions