是否可以在Month()中指定条件?

时间:2015-03-14 09:49:01

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

我想只显示例如Months ='1'

的行
select IssueAmount, MONTH( CONVERT(date, IssueDate )) as Months
from LoanAccount

如果我添加 where 条件,我会收到以下错误消息:

****'Msg 207,Niveau 16,État1,Ligne 4 Nom de colonne non valide:'Months'。'****

这是我正在使用的代码:

select IssueAmount, MONTH( CONVERT(date, IssueDate )) as Months
from LoanAccount where Months = '1'

3 个答案:

答案 0 :(得分:2)

您不能在alias select statement same子句中使用where名称,因为where子句在evaluated之前是select所以别名在where条款中无法使用。因此,直接使用month子句

中的where函数
select IssueAmount,  Month(CONVERT(date, IssueDate ))
from LoanAccount where Month(CONVERT(date, IssueDate )) = 1

或将查询设为sub-select并使用alias名称过滤outer query

中的记录
select * from 
(
select IssueAmount, datepart(CONVERT(date, IssueDate ), IssueDate )  as Months
from LoanAccount
) a
where Months =1

答案 1 :(得分:1)

不允许在WHERE子句

中使用结果列的别名

试试这个:

select 
    IssueAmount, 
    MONTH(CONVERT(date, IssueDate)) as Months
from LoanAccount 
where MONTH(CONVERT(date, IssueDate)) = 1

答案 2 :(得分:0)

使用SQL datepart

e.g

select datepart(month,getdate())

您的查询应该是这样的。

select IssueAmount, datepart(month, IssueDate ) as Months
from LoanAccount where datepart(month, IssueDate )= 1