Last active
November 30, 2017 07:14
-
-
Save DanielLoth/2941dfca48c217bb83f1711844f2dae6 to your computer and use it in GitHub Desktop.
SQL Server data pivot (rows to columns)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- 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