SQL Select在使用现有列作为引用的Select中进行选择,

SQL Select在使用现有列作为引用的Select中进行选择,,sql,sql-server,sql-server-2008,sql-server-2012,Sql,Sql Server,Sql Server 2008,Sql Server 2012,我有一张像这样的桌子 | ItemCode | AvgPrice | PriceList | ComplimentaryItemCode | | AL01 | 22 | 1 | AL02 | | AL02 | 19 | 1 | AL03 | | AL03 | 7 | 1 | AL01

我有一张像这样的桌子

| ItemCode | AvgPrice | PriceList | ComplimentaryItemCode |
| AL01     | 22       | 1         | AL02                  |
| AL02     | 19       | 1         | AL03                  | 
| AL03     |  7       | 1         | AL01                  |
| BA01     | 50       | 1         | NULL                  |
| BA01     | 60       | 1         | BA01                  |
我想在查询中创建一个额外的列,向我显示恭维ItemCode的AvgPrice,如下所示

| ItemCode | AvgPrice | PriceList | ComplimentaryItemCode | AvgPriceComplimentary
| AL01     | 22       | 1         | AL02                  |   19 
| AL02     | 19       | 1         | AL03                  |    7
| AL03     |  7       | 1         | AL01                  |   22
| BA01     | 50       | 1         | NULL                  | null
| BA01     | 60       | 1         | BA01                  |   50
到目前为止,我尝试了这个,但没有运气

SELECT     a.ItemCode, a.AvgPrice,  t.PriceList,  a.ComplimentaryItemCode,
                          (SELECT     AvgPrice
                            FROM          MATERIALS AS a
                            WHERE      (ItemCode = ComplimentaryItemCode)) AS AvgPriceComplimentary
FROM         MATERIALS AS a LEFT OUTER JOIN
                      PRICES AS t ON t.ItemCode = a.ItemCode AND t.PriceList = 1
WHERE     (T.PriceList <> 107) AND (T.PriceList <> 108)

任何帮助都太好了

您应该为此使用窗口函数:

SELECT m.ItemCode, m.AvgPrice, p.PriceList, m.ComplimentaryItemCode,
       AVG(AvgPrice) OVER (PARTITION BY ComplimentaryItemCode)  as AvgPriceComplimentary
FROM MATERIALS m LEFT OUTER JOIN
     PRICES p ON t.ItemCode = m.ItemCode AND t.PriceList = 1
WHERE p.PriceList NOT IN (107, 108) ;
为相关子查询中的表添加top 1并使用不同的别名:

select 
    a.ItemCode
  , a.AvgPrice
  , t.PriceList
  , a.ComplimentaryItemCode
  , (
   select top 1 AvgPrice
   from MATERIALS as i
   where (i.ItemCode = a.ComplimentaryItemCode)
   ) as AvgPriceComplimentary
from MATERIALS as a
  left join PRICES as t 
    on t.ItemCode = a.ItemCode 
   and t.PriceList = 1    /* if t.PriceList = 1, why the following where? */
where T.PriceList <> 107
  and T.PriceList <> 108