无法使用在左连接SQL中使用交叉应用创建的临时列

时间:2017-11-27 21:13:17

标签: sql sql-server join cross-apply

我使用Cross apply将数据从宽幅翻转到高大格式。使用以下问题的答案来实施Using PIVOT to Flip Data from Wide to Tall

我创建了临时列Sector。我想将此列用于左连接与另一个表。但是我在这一行Invalid column name 'Sector'

上收到错误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] 

任何人都可以帮我解决这个问题。谢谢!

2 个答案:

答案 0 :(得分:2)

您需要参考cross apply别名:

[Economic_Data].[dbo].[Sector level] S
on V.Sector = x.[Sector name] 
--------------^

答案 1 :(得分:1)

看起来你需要删除最后一个逗号。

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]