SQL - How to transfor records into a single records
I have records of person doing business in difference state, I like to create a single person records with state as column of Boolean value.
for example
I have the following records
Name | State
----------------------
Person1 | NY
Person1 | WI
Person1 | GA
Person2 | SD
Person2 |WI
Person3 | FL
I like to create record of the following
Name | NY |WI|MI|SD|GA|FL
----------------------------------------------
Person1 | T | T | F | F | T | F
Person2 | F | T | F | T | F | F
Person3 | F | F | F | F | F | T
DECLARE @columns VARCHAR(8000) DECLARE @columns2 VARCHAR(8000) DECLARE @sql NVARCHAR(MAX) SET @Columns = SUBSTRING((SELECT DISTINCT ',['+state+']' FROM tbl GROUP BY state FOR XML PATH('')),2,8000) SET @Columns2 = SUBSTRING((SELECT DISTINCT ',case when ['+state+'] is null then ''F'' else ''T'' end AS ['+state+']' FROM tbl GROUP BY state FOR XML PATH('')),2,8000) SET @SQL = 'SELECT [Name],' + @Columns2 + ' FROM (Select [Name], state from tbl ) SourceData PIVOT (min(state) for state in ('+@Columns+')) pivottable ' EXEC(@sql)
what I find is if I have more than Name and State as columns, SQL server will complain with this error
Msg 8120, Level 16, State 1, Line 1
Column 'dbo.table_1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
The select statement is as follows
select name, address,
max (case when State ='NY' Then 'T' else 'F' end) as NY,
max(case when State ='WI' Then 'T' else 'F' end) as WI,
max(case when State ='MI' Then 'T' else 'F' end) as MI,
max(case when State ='SD' Then 'T' else 'F' end) as SD,
max(case when State ='GA' Then 'T' else 'F' end) as GA,
max(case when State ='FL' Then 'T' else 'F' end) as FL
From table_1
group by name
Open in new window