Я пытаюсь использовать Pivot, чтобы поместить значения avg для каждого региона в столбцы, я не знаю, как создать его для моих данных, как это можно решить?Проблема в том, что когда я пытаюсь запустить приведенный ниже код, я получаю эту ошибку
Сообщение 102, Уровень 15, Состояние 1, Строка 14
Неверный синтаксис рядом с 'sq'.
Я не знаю, что нужно сделать, чтобы повернуть это.
DECLARE @MovingAverageQty AS INT;
DECLARE @SkipQtyDays AS INT;
SET @MovingAverageQty = 4;
SET @SkipQtyDays = @MovingAverageQty + 22;
DROP TABLE #solveAvg;
CREATE TABLE #solveAvg
(
Id INT IDENTITY(1, 1),
Date DATE,
FDate DATE,
Avg1 DECIMAL(13, 8),
Avg2 DECIMAL(13, 8),
DataSource VARCHAR(100),
Region VARCHAR(100)
);
DECLARE @SQLStr VARCHAR(5000);
SET @SQLStr = '';
SELECT
@SQLStr = @SQLStr + '[' + [a].[Column] + '], '
FROM
(SELECT DISTINCT
Region AS [Column]
FROM PriceQuote) AS a;
SET @SQLStr = LEFT(@SQLStr, LEN(@SQLStr) - 1);
INSERT INTO #solveAvg (Date, FDate, Avg1, Avg2, DataSource, Region)
SELECT
Date AS d,
NULL,
AVG(Price) OVER (ORDER BY Date ASC ROWS 4 PRECEDING) AS AvgPrice,
0,
DataSource,
Region
FROM
PriceQuote
WHERE
ProductId = 15
AND DataSource NOT IN ('MaisBolsas', 'QueroBolsa');
UPDATE a
SET a.Avg2 = b.Avg1,
FDate = b.Date
FROM #solveAvg a
INNER JOIN #solveAvg b ON a.Id = b.Id - @SkipQtyDays;
SET @SQLStr = 'Select s.FDate as Date, Case when s.Avg1 = 0 then 0 else ((s.Avg2/s.Avg1) - 1)*100 end as series, i.Value as ponta,' + @SQLStr + ' from (#solveAvg s inner join ipca i on s.FDate = i.Date and i.ProductId = 15) sq PIVOT (series for Region in (' + @SQLStr + ')) as pt';
PRINT @SQLStr;
EXEC (@SQLStr);
РЕДАКТИРОВАТЬ 2: Вот печать @SqlStr:
Select s.FDate as Date, i.Value as ponta,[ILHEUS], [TEIXEIRA DE FREITAS], [JAGUAQUARA], [CRUZ DAS ALMAS], [FEIRA DE SANTANA], [EUNAPOLIS], [VITORIA DA CONQUISTA], [RIBEIRA DO POMBAL], [IRECE], [TUCANO], [ITABUNA], [LUIS EDUARDO MAGALHAES], [VALENTE], [SANTO ANTONIO DE JESUS], [LIVRAMENTO DE NOSSA SENHORA], [JUAZEIRO], [CHICAGO/USA], [ITAPETINGA], [SALVADOR], [VALENCA], [BARREIRAS], [ADUSTINA], [INHAMBUPE], [JEQUIE] from (#solveAvg s inner join ipca i on s.FDate = i.Date and i.ProductId = 15) sq PIVOT (Case when s.Avg1 = 0 then 0 else ((s.Avg2/s.Avg1) - 1)*100 end for Region in ([ILHEUS], [TEIXEIRA DE FREITAS], [JAGUAQUARA], [CRUZ DAS ALMAS], [FEIRA DE SANTANA], [EUNAPOLIS], [VITORIA DA CONQUISTA], [RIBEIRA DO POMBAL], [IRECE], [TUCANO], [ITABUNA], [LUIS EDUARDO MAGALHAES], [VALENTE], [SANTO ANTONIO DE JESUS], [LIVRAMENTO DE NOSSA SENHORA], [JUAZEIRO], [CHICAGO/USA], [ITAPETINGA], [SALVADOR], [VALENCA], [BARREIRAS], [ADUSTINA], [INHAMBUPE], [JEQUIE])) as pt