【问题标题】:SQL Select inside Select using an existing column as reference,SQL Select inside Select 使用现有列作为参考,
【发布时间】:2017-04-07 19:19:48
【问题描述】:

我有一张像这样的桌子。

| ItemCode | AvgPrice | PriceList | ComplimentaryItemCode |
| AL01     | 22       | 1         | AL02                  |
| AL02     | 19       | 1         | AL03                  | 
| AL03     |  7       | 1         | AL01                  |
| BA01     | 50       | 1         | NULL                  |
| BA01     | 60       | 1         | BA01                  |

我想在查询中创建一个额外的列来显示 ComplimentaryItemCode 的 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)

任何帮助都会很棒!

【问题讨论】:

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


    【解决方案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) ;
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-14
        • 1970-01-01
        • 1970-01-01
        • 2018-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-29
        相关资源
        最近更新 更多