Very new to SQL Server, at this time I want to use a query with a Pivot table but something is bat, Is there some one could be help me to find my error I appreciate. Regards In the first part I create a dummy table called DateTemp
in the second part, I join two tables the DateTemp
and datcpc
tables, now I want to use a pivot table, but I get an error near to pivot section.
My code:
// First Part
DECLARE @StartDate datetime
DECLARE @EndDate datetime
SELECT @StartDate = '2018-01-01', @EndDate = '2018-11-08'
SELECT @StartDate = @StartDate - (DATEPART(DD, @StartDate) - 1)
DECLARE @DateTemp TABLE (TheDate DATETIME)
WHILE (@StartDate <= @EndDate)
BEGIN
INSERT INTO @DateTemp
VALUES (@StartDate)
SELECT @StartDate = DATEADD(DAY, 1, @StartDate)
END
// Second part
SELECT
CYALA, CYALB
FROM
(SELECT DISTINCT
fechab 'FECHA', clapla 'CLAVEPLANTA', clapro 'CLAVE PRODUCTO',
CAST(SUM(cantid) AS NUMERIC(9, 2)) 'ACTIVIDAD'
FROM
(datcpc
LEFT JOIN
(SELECT TheDate
FROM @DateTemp
WHERE TheDate >= '05/01/2018') NT ON datcpc.fechab = NT.TheDate)
WHERE
datcpc.fechab >= '01/05/2018'
AND datcpc.fechab >= '01/05/2018'
AND (clapla = 'CYALA' OR clapla = 'CYALB' OR clapla = 'CYAZC')
AND datcpc.tipflu = 'C'
GROUP BY
fechab, clapla, clapro) AS SOURCE
PIVOT
(SUM(SOURCE.ACTIVIDAD)
FOR SOURCE.CLAVEPLANTA IN (CYALA, CYALB)
) AS PIVOTABLE
Test the suggested answers, without success. Try a simpler example and even then the error is set as "System.Data.SqlClient.SqlException: 'Line 1: Incorrect syntax near 'PIVOT'.'", I do not know if it is the server configuration or something about it. I use a connection to the server via Visual Studio 2017 via SqlConnection my new easier codes is listed below
SELECT DISTINCT [CLAVEPLANTA], [ACTIVIDAD]
FROM(
SELECT fechab AS [FECHA], clapla AS [CLAVEPLANTA], CAST(SUM(cantid) AS NUMERIC(9,2) ) AS [ACTIVIDAD] FROM datcpc"
WHERE datcpc.fechab >= '01/05/2018'
AND (clapla='CYALA' OR clapla='CYALB' OR clapla='CYAZC')
GROUP BY fechab, clapla
) AS [SO]
PIVOT(SUM([SO.ACTIVIDAD]) FOR [SO.CLAVEPLANTA] IN ([CYALA], [CYALB])) AS [PVT];
I really apreciate you help