0

I have used Cross apply to Flip data from Wide to Tall format. Used answer from following question to implement Using PIVOT to Flip Data from Wide to Tall

I have created temporary column Sector. I want to use this column for Left Join with another table. But i am getting error Invalid column name 'Sector' on this line V.Sector = S.[Sector name]

SELECT Date,
      Country,
      Sector,
      PE,
      PX_BOOK
      S.Sector_level
FROM [Economic_Data].[dbo].[Sector_Valuations] V
CROSS APPLY 
(
  VALUES
    ('Large Cap Equity',[Large Cap Equity_PE],[Large Cap Equity_book]),
    ('Mid Cap Equity',[Mid Cap Equity_PE],[Mid Cap Equity_book]),
    ('Small Cap Equity',[Small Cap Equity_PE],[Small Cap Equity_book]),
    ('Value Index',[Value Index_PE],[Value Index_book]),
    ('Growth Index',[Growth Index_PE],[Growth Index_book]),
    )  x (Sector, PE, PX_BOOK)  
 Left join [Economic_Data].[dbo].[Sector level] S
 on  V.Sector = S.[Sector name] 

Can anybody help me to fix this issue. Thanks!

Arvinth Kumar
  • 964
  • 3
  • 15
  • 32

2 Answers2

2

You need to refer to the cross apply alias:

[Economic_Data].[dbo].[Sector level] S
on V.Sector = x.[Sector name] 
--------------^
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

Its looks like you need remove the last comma.

SELECT Date,
      Country,
      Sector,
      PE,
      PX_BOOK
      S.Sector_level
FROM [Economic_Data].[dbo].[Sector_Valuations] V
CROSS APPLY 
(
  VALUES
    ('Large Cap Equity',[Large Cap Equity_PE],[Large Cap Equity_book]),
    ('Mid Cap Equity',[Mid Cap Equity_PE],[Mid Cap Equity_book]),
    ('Small Cap Equity',[Small Cap Equity_PE],[Small Cap Equity_book]),
    ('Value Index',[Value Index_PE],[Value Index_book]),
    ('Growth Index',[Growth Index_PE],[Growth Index_book])--, <------
    )  x (Sector, PE, PX_BOOK)  
 Left join [Economic_Data].[dbo].[Sector level] S
 on  V.Sector = S.[Sector name] 
Nolan Shang
  • 2,312
  • 1
  • 14
  • 10