Skip to content

Instantly share code, notes, and snippets.

@DanielLoth
Last active November 30, 2017 07:14
Show Gist options
  • Select an option

  • Save DanielLoth/2941dfca48c217bb83f1711844f2dae6 to your computer and use it in GitHub Desktop.

Select an option

Save DanielLoth/2941dfca48c217bb83f1711844f2dae6 to your computer and use it in GitHub Desktop.
SQL Server data pivot (rows to columns)
-- Based on this article: http://modern-sql.com/use-case/pivot
set nocount on
declare @Table table (
TableName char(20),
AttributeName char(20),
AttributeValue char(20),
-- Mandatory: Each attribute must appear precisely once for each element.
-- Otherwise the MAX aggregate will potentially return incorrect values.
primary key (TableName, AttributeName)
)
insert into @Table (TableName, AttributeName, AttributeValue) values
('Table1', 'Name', 'XXX'),
('Table1', 'Description', 'YYY'),
('T2', 'Name', 'hello'),
('T2', 'Description', 'desc')
select
TableName,
Name = max(case when AttributeName = 'Name' then AttributeValue end),
Description = max(case when AttributeName = 'Description' then AttributeValue end)
from @Table
group by TableName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment