在Sql中引用别名列

时间:2013-12-13 09:22:10

标签: sql sql-server

我需要在sqlserver中引用别名列。这里'dob'是来自tbl_Student_Admission表的出生日期列

Select DATEPART(yy, dob) as years 
From dbo.tbl_Student_Admission 
Where years between '1990' and '1992'

6 个答案:

答案 0 :(得分:3)

只需使用第二个SELECT:

select * from (
  select DATEPART(yy, dob) as years from dbo.tbl_Student_Admission
) v1
where years between '1990' and '1992'

请注意,通过为BETWEEN使用字符串,您强制数据库将DATEPART的结果转换为字符串,这通常会导致性能下降。所以你应该使用普通数字代替:

select * from (
  select DATEPART(yy, dob) as years from dbo.tbl_Student_Admission
) v1
where years between 1990 and 1992

SQL Fiddle

答案 1 :(得分:3)

你可以像这样使用它......

select * from (
select DATEPART(yy, dob) as years from dbo.tbl_Student_Admission 
) abc
where years between '1990' and '1992'

但这不是一个好方法......它会降低你的查询性能。所以你应该使用以下查询..

select DATEPART(yy, dob) as years from dbo.tbl_Student_Admission where DATEPART(yy, dob) between '1990' and '1992'

答案 2 :(得分:3)

有一种非常简单的方法。那么为什么要复杂呢?你应该这样试试。这将有效。

Select DATEPART(yy, dob) as 'years' 
From dbo.tbl_Student_Admission 
Where DATEPART(yy, dob) between '1990' and '1992'

答案 3 :(得分:1)

与其他编程语言不同的SQL的第一个值得注意的方面是 处理代码的顺序。在大多数编程语言中,代码都会被处理 按照写入的顺序。在SQL中,处理的第一个子句是

FROM clause,then Where -> Group By -> Having-> Select -> Order By

所以首先出现的SELECT子句几乎是最后处理的。因此,您无法从where子句中的选择列表中引用别名列年份,因为它尚未计算。 你应该把它写成:

select [years] from (
select DATEPART(yy, dob) as years 
from dbo.tbl_Student_Admission 
) T
where T.years between 1990 and 1992

答案 4 :(得分:0)

CTE是另一种选择:

WITH myCTE 
    AS
    (
    SELECT  years = DATEPART(yy, dob)
    FROM    dbo.tbl_Student_Admission
    )
SELECT  *
FROM    myCTE
WHERE   years BETWEEN 1990 AND 1992 

答案 5 :(得分:0)

cross apply

的解决方案
SELECT t.*, c.y
FROM dbo.tbl_Student_Admission t
CROSS APPLY
(
 SELECT DATEPART(yy, t.years) as y
) c
WHERE c.y between 1990 and 1994