Пример данных
IF OBJECT_ID('tempdb..#TempTab')IS NOT NULL
DROP TABLE #TempTab
;WITH CTE_Temp (rut ,fecha ,monto ,tipo)
AS
(
SELECT 123 ,'01/02/2018' , 125000 , 'SMS' UNION ALL
SELECT 123 ,'01/05/2014' , 32500 , 'FOLLETO' UNION ALL
SELECT 123 ,'01/04/2015' , 255000 , 'IA' UNION ALL
SELECT 123 ,'01/02/2015' , 132850 , 'FOLLETO' UNION ALL
SELECT 127 ,'01/07/2016' , 75000 , 'LIQUIDACION' UNION ALL
SELECT 123 ,'01/08/2018' , 55000 , 'SMS' UNION ALL
SELECT 123 ,'01/05/2018' , 180000 , 'SMS' UNION ALL
SELECT 123 ,'01/12/2017' , 700000 , 'FOLLETO' UNION ALL
SELECT 123 ,'01/11/2016' , 653200 , 'SMS' UNION ALL
SELECT 784 ,'01/03/2015' , 88000 , 'FOLLETO' UNION ALL
SELECT 123 ,'01/10/2017' , 60500 , 'SMS'
)
SELECT * INTO #TempTab
FROM
(
SELECT *,
DATENAME(MONTH,CONVERT(DATE,fecha,103)) MyMonths
FROM CTE_Temp
)dt
При использовании Dynamic sql
DECLARE @Column nvarchar(1000),@Column2 nvarchar(max),
@Sql nvarchar(max)
SELECT @Column =STUFF((SELECT ', '+QUOTENAME(MonthName)
FROM
(
SELECT DATENAME(MONTH, DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthName],
MONTH(DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthNumber]
FROM master.dbo.spt_values s
WHERE [type] = 'P' AND s.number BETWEEN 0 AND 11
)dt
FOR XML PATH ('')),1,1,'')
SELECT @Column2 = STUFF((SELECT ', '+'MAX('+QUOTENAME(MonthName) +') AS '+QUOTENAME(MonthName)
FROM
(
SELECT DATENAME(MONTH, DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthName],
MONTH(DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthNumber]
FROM master.dbo.spt_values s
WHERE [type] = 'P' AND s.number BETWEEN 0 AND 11
)dt
FOR XML PATH ('')),1,1,'')
SELECT @Sql = 'SELECT DATEPART(YEAR,fecha) AS [Year],
MAX(rut) AS [Rut],
MAX(tipo) AS tipo,'+@Column2 +'
FROM
(
SELECT * FROM #TempTab
) AS SRc
PIVOT
(
MAX(monto) FOR MyMonths IN ('+@Column+')
) AS pvt
GROUP BY DATEPART(YEAR,fecha)
ORDER BY [Year]
'
PRINT @Sql
EXEC (@Sql)
Результат
Year Rut tipo January February March April May June July August September October November December
---------------------------------------------------------------------------------------------------------------------------------
2014 123 FOLLETO NULL NULL NULL NULL 32500 NULL NULL NULL NULL NULL NULL NULL
2015 784 IA NULL 132850 88000 255000 NULL NULL NULL NULL NULL NULL NULL NULL
2016 127 SMS NULL NULL NULL NULL NULL NULL 75000 NULL NULL NULL 653200 NULL
2017 123 SMS NULL NULL NULL NULL NULL NULL NULL NULL NULL 60500 NULL 700000
2018 123 SMS NULL 125000 NULL NULL 180000 NULL NULL 55000 NULL NULL NULL NULL