I have a query which works fine, but I am trying to create a dynamic pivot out of it to get a better end result table.
I found this on SO but I cant relate it to my issue. The multi-part identifier could not be bound
My working code is this:
DECLARE @RangeDate as date
set @RangeDate = (select distinct cd.weDate from CM_DATA cd where cd.year = 2015 and cd.week = 45)
set @RangeDate = DATEADD(WW, -7, @RangeDate)
DECLARE @SQL as VARCHAR(MAX)
DECLARE @Columns AS VARCHAR(MAX)
SELECT @Columns =
COALESCE(@Columns + ', ','') + QUOTENAME(YearWeek)
FROM
(
SELECT DISTINCT YearWeek
FROM CM_DATA
where weDate >= @RangeDate
) AS B
SET @SQL = '
WITH PivotData AS
(
select cd.Country
, cd.Chain
, cd.YearWeek
, left(sm.Planogram, 2) as planogram
, cd.StoreNo
, cd.UID
, cd.ShortCode
, lp.Family
, lp.ColourShort
, pr.type
, cd.Volume
, ul.WOSOR
from vw_V2_UsrVarLst ul
left join CM_DATA cd on cd.Country = ul.CountryCode and cd.Chain = ul.Chain
left join V2_StoreMaster sm on sm.CountryCode = ul.CountryCode and sm.Chain = ul.Chain and sm.StoreNo = cd.StoreNo and sm.StoreNm = cd.StoreNm and cd.YearWeek between sm.YYYYWW and sm.YYYYWWEND
left join tblProducts pr ON pr.[COUNTRY CODE] = ul.CountryCode and pr.SKU = cd.UID
left join V2_LanguagePack LP ON LP.ShortCode = cd.ShortCode AND lp.Lang = ul.UsrLang
where cd.Country = ul.CountryCode and cd.Chain = ul.Chain and planogram is not null and left(cd.UID, 10) in (select lv.UID from V2_live lv where lv.CountryCode = ul.CountryCode and lv.Chain = ul.Chain and cd.YearWeek between lv.YYYYWW and lv.YYYYWWEND) and cd.weDate >= ' + @RangeDate + ' and sm.Planogram != ''Z''
)
select cd.Country
, cd.Chain
, left(sm.Planogram, 2) as planogram
, cd.StoreNo
, cd.UID
, cd.ShortCode
, lp.Family
, lp.ColourShort
, pr.type
, cd.Volume
, ' + @Columns + '
, ul.WOSOR
FROM PivotData
PIVOT
(
SUM(Volume)
FOR YearWeek
IN(' + @Columns + ')
) AS PivotResult'
EXEC (@SQL)
Can anyone spot what up here
KR Martin