您可以使用关键字“AS”和select语句重命名表吗?

时间:2010-07-05 14:11:39

标签: sql

这对大多数人来说可能是一个愚蠢的问题,但我想知道你是否可以使用'AS'关键字和select语句重命名列?

这是我的SQL:

Select Main.EmpId
        , Associate_List.costCenter, Assignments.Area
        , Main.Assignments_1 AS (
            Select Assignment_Name 
                from Assignments 
                where Assignment_Number = 1 
                    and Assignments.Area = '@Someparemeter'
        )
from associate_list
    , main
    , APU_CC
    , Assignments 
where Main.Empid = Associate_List.Empid 
    and substring(Associate_List.CostCenter,1,4) = APU_CC.CostCentre

我想知道的SQL的唯一部分是:

Main.Assignments_1 AS (
    Select Assignment_Name 
        from Assignments 
        where Assignment_Number = 1 
            and Assignments.Area = '@Someparemeter'
)

这是可能还是我说的是胡言乱语,还是这只是一件愚蠢的事?

非常感谢

4 个答案:

答案 0 :(得分:1)

as之后的部分不是值而是变量名称; SQL数据库将使用它来引用结果集的值,以便您可以比较/排序/过滤它们。因此,这是不可能的。

如果必须这样做,则必须阅读数据库的文档,以了解如何构建动态查询。但我建议反对它,因为它会导致很难调试的奇怪错误。

答案 1 :(得分:0)

我不太清楚你在开什么车。

如果主表中有一个名为Assignments_1的列,您可以在查询中重命名该列(在输出顶部提供不同的标题或出于其他原因),如下所示...

SELECT MAIN.ASSIGNMENT_1 AS MY_NEW_NAME
    FROM etc.

如果您想在查询中使用派生表,请将其命名为......

SELECT MAIN.ASSIGNMENT_1,
       SELECT *
           FROM (SELECT THIS, THAT, THE_OTHER
                     FROM SOME_TABLE) AS DERIVED_TABLE
    FROM etc.

如果您不想要其中任何一项,请澄清,我们会尽力提供帮助。

答案 2 :(得分:0)

但你可以这样做:

Select m.EmpId, l.costCenter, 
 (Select Area From Assignments a 
  Where Assignment_Number = 1 
     And Area = '@Someparemeter') As Area, 
 (Select Assignment_Name From Assignments a 
  Where Assignment_Number = 1 
     And Area = '@Someparemeter') As Assignments_1
From associate_list l 
   Join main m On m.Empid = l.Empid  
   Join APU_CC c On c.CostCentre = substring(l.CostCenter,1,4)

或者这个:

Select m.EmpId, l.costCenter, Asgn.Area,
  Asgn.Assignment_Name as Assignments_1 
From associate_list l 
   Join main m On m.Empid = l.Empid  
   Join APU_CC c On c.CostCentre = substring(l.CostCenter,1,4)
   Cross Join (Select Assignment_Name From Assignments a 
               Where Assignment_Number = 1 
                  And Area = '@Someparemeter') as Asgn

答案 3 :(得分:0)

在SQL Server中,您可以为具有AS的列分配别名,如下所示:

...
ColumnName AS ColumnAlias,
...

你可以像你在你的例子中那样进行“子选择”。 (我不会像那样编写查询 - 我先运行子查询,然后将结果放到第二个查询中,如下所示:

DECLARE @Assignment_Name varca(100) -- or however long

SELECT @Assignment_Name = Assignment_Name
 from Assignments
 where Assignment_Number = 1
  and Assignments.Area = @Someparemeter

SELECT
 ...
 @Assignment_Name = Assignment_Name,
 ...