I have done a pivot on a table, generating dynamic columns :
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT d
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(Replace(variable,char(CAST(0x0016 as int)),'')) val
FROM TABLEDATA
ORDER BY val asc
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @query =
'SELECT
time,
country,
disease,
' + @cols + '
FROM (
Select
time,
country,
disease,
variable,
convert(decimal(10, 2), value) as value
From
TABLEDATA
) t
PIVOT
(
Sum(value)
FOR variable IN( ' + @cols + ' )' +
' ) AS p; ';
Execute(@query);
Example Fiddle