Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sql pivot function not allow integers as column names?

I'm trying to do a fairly symbol pivot. This one runs as expected:

with cte as
(
    select Symbol, TradeDate, 'Per' + cast(Period as CHAR(3)) Per, Value
    from tblDailySMA
)

select * from cte
pivot
(Max(Value) for Per in (Per5,Per10,Per15,Per20,Per30,Per40,Per50,Per60,Per80,Per100,Per110,Per120,
    Per150,Per200)) pvt

and this one gives the error Incorrect syntax near 5 (and highlights the the first value (5) after 'for Period in':

with cte as
(
    select Symbol, TradeDate, Period, Value
    from tblDailySMA
)

select * from cte
pivot
(Max(Value) for Period in (5,10,15,20,30,40,50,60,80,100,110,120,150,200)) pvt

I got the first one to run after much trial and error... is there a reason, such as perhaps integer values not being allowed as column names? Thanks..

like image 242
StatsViaCsh Avatar asked Jan 16 '23 15:01

StatsViaCsh


1 Answers

You should always place square brackets around the column names []:

with cte as
(
    select Symbol, TradeDate, Period, Value
    from tblDailySMA
)

select * from cte
pivot
(
   Max(Value) for Period in ([5],[10],[15],[20],[30],[40],[50],[60],[80],[100],[110],[120],[150],[200])
) pvt

From MSDN:

The first character must be one of the following:

  • A letter as defined by the Unicode Standard 3.2. The Unicode definition of letters includes Latin characters from a through z, from A through Z, and also letter characters from other languages.
  • The underscore (_), at sign (@), or number sign (#).

If it is anything else, then you will need to use the square brackets. []

like image 171
Taryn Avatar answered Jan 24 '23 20:01

Taryn