Your SELECT * needs to be whatever the complex query is that created the result in your Image (.eg. a PIVOT or somesuch), not just a query of the two columns from the original table.
If it helps you can use a wrapper query:
SELECT X.*
INTO NewTable
FROM
(
SELECT .... complex query ....
FROM ...
...
) AS X
set @fields=stuff((select ',['+Dateformat1+']'
from pricetobook
where Dateformat1 not in ('Code','Mnemonic')
group by Dateformat1
order by case when Dateformat1='Name' then 0 else 3 end
,Dateformat1
for xml path('')
,type
).value('.','nvarchar(max)')
,1
,1
,''
)
;
print @fields
set @sql='
select '+@fields+'
from (select Dateformat1
,Dataformat2
,sum(rn1*rn2) over(order by rn2) as rn
from (select Dateformat1
,Dataformat2
,case when Dateformat1=''Name'' then 1 else 0 end as rn1
,row_number() over(order by (select null)) as rn2
from pricetobook
) as a
) as a
pivot (max(Dataformat2) for Dateformat1 in ('+@fields+')) as p
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'select'.
Msg 156, Level 15, State 1, Line 54
Incorrect syntax near the keyword 'from'.
The second half of that is not my solution, that's some completely different Dynamic SQL !!
PRINT the @sql variable before the execute sp_executesql @sql statement and see what it contains. You should be able to, manually, execute that SQL and then debug it and, once fixed, feed back those changes into your Dynamic SQL preparation statement
You've missed off part of my code in the first part. If that is not a typo in your message here then fixing that may help. Suggest you run the first part, separately, until that is debugged before you add on the second, more complex, part.