SQL Select inside选择使用现有列作为参考,

时间:2017-04-07 19:19:49

标签: sql sql-server sql-server-2008 sql-server-2012

我有一张看起来像这样的表。

index.html

我想在查询中创建一个额外的列,以显示ComplimentaryItemCode的AvgPrice,就像这样;

| 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 | 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

任何帮助都会很精彩!

2 个答案:

答案 0 :(得分:1)

您应该使用窗口函数:

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) ;

答案 1 :(得分:0)

在相关子查询中为表添加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