如何在嵌套子查询中使用外部字段名称或别名

时间:2017-09-19 13:44:22

标签: sql sql-server

我会在子查询中使用选定的字段Referencia。

我尝试将字段名称包含在别名和表名中但不起作用。

我怎么能做到这一点?

由于

SELECT * FROM
(
    SELECT
      articulos.Codigo AS Referencia,    
      articulos.Nombre AS Descripcion,
      barras.Codigo AS [Codigo de Barras],
      ROW_NUMBER() OVER (PARTITION BY articulos.Codigo ORDER BY 
      articulos.Codigo ASC) as cantidad,
      articulos.Familia,
      articulos.Marca,              
      categorias.Codigo as Categoria,
      articulos.ImpuestoEspecial AS Ecotasa,
      articulos.Fase,
      articulos.Iva,
     --
     -- Tarifa1
     (  SELECT [Codigo],[EuroPrecio]
        FROM [GES16100].[dbo].[Tarifas] 
        WHERE [Codigo] = 1 AND [Articulo] = <------- Here, Referencia
     )AS T1,    
     articulos.Proveedor,
     articulos.GUID_Registro
     FROM [GES16100].[dbo].[Articulos] as articulos
        FULL JOIN [GES16100].[dbo].[Barras] as barras
            ON articulos.Codigo = barras.Articulo
        FULL JOIN [GES16100].[dbo].[Categorias_Asignaciones] catasignaciones
            ON catasignaciones.GUID_RegistroFichero =articulos.GUID_Registro                    
        FULL JOIN [GES16100].[dbo].[CategoriasFicheros] categorias
            ON categorias.GUID_Registro = catasignaciones.GUID_Categoria                                

)AS supersub
WHERE supersub.cantidad = 1

1 个答案:

答案 0 :(得分:1)

只要查询中有多个表,就使用表别名和限定列名。

其次,您的子查询将无法工作,因为它返回两列,其中一个是预期的。

对于你的例子,我猜:

( SELECT t.EuroPrecio
   FROM [GES16100].[dbo].[Tarifas]  t
   WHERE t.Codigo = 1 AND t.Articulo = a.Codigo
) AS T1,    

您不能使用列别名Referencias,因为它是在同一SELECT中定义的。只需使用它所引用的列。