The problem you are having is not
entirely code based, it is a problem with using
reserved/special names for your columns.
One of the rules that I use is that if a particular column-name displays in a different color than the rest in an intellisense environment, it either needs to be changed or properly escaped.
Notice that even in the CP editor which does not have all of the SQL definitions in it that "Date" is a different color. In my local editor "Value" also changes color
CREATE TABLE mytable(
ID INT NOT NULL
,Bussiness VARCHAR(3) NOT NULL
,Date VARCHAR(10) NOT NULL
,Value INT NOT NULL
);
My normal routine would be then to change the names of the offending columns; so that is what I did in this test of your code and it all worked out, and I got the results you desired
DECLARE @mytable TABLE (
ID INT NOT NULL
,Bussiness VARCHAR(3) NOT NULL
,mDate VARCHAR(10) NOT NULL
,mValue INT NOT NULL
);
INSERT @mytable( ID,Bussiness, mDate, mValue) VALUES
(1,'GPS','Nov-18',3 )
,(2,'GPS','Dec-18',2 )
,(3,'GPS','Nov-18',2 )
,(4,'GPS','Dec-18',3 );
;with cte as(
select row_number()over(partition by mDate order by ID) ID,
Bussiness, mDate, mValue
from @mytable
)
SELECT *
FROM cte
PIVOT (
MAX([mValue])
FOR mDate IN ( [Nov-18],[Dec-18])
) AS pvt
If you cannot change the names, then you need to wrap the offending columns in [square brackets], and running this code also produces the desired results
DECLARE @mytable TABLE (
ID INT NOT NULL
,Bussiness VARCHAR(3) NOT NULL
,[Date] VARCHAR(10) NOT NULL
,[Value] INT NOT NULL
);
INSERT @mytable( ID,Bussiness, [Date], [Value]) VALUES
(1,'GPS','Nov-18',3 )
,(2,'GPS','Dec-18',2 )
,(3,'GPS','Nov-18',2 )
,(4,'GPS','Dec-18',3 );
;with cte as(
select row_number()over(partition by [Date] order by ID) ID,
Bussiness, [Date], [Value]
from @mytable
)
SELECT *
FROM cte
PIVOT (
MAX([Value])
FOR [Date] IN ( [Nov-18],[Dec-18])
) AS pvt
And while it is not causing a problem in this instance; you should always use the proper Data Types; storing dates as text removes a lot of the features of the Date type, such as sorting and arithmetic operations.