我有个问题如下-
select distinct datepart(yy, a.date_created) as year, datepart(mm, a.date_created) as month, concat(month, '-', year) as monthyr
from dbo.assignment a所以,我想在这里做的是,我得到了年份部分日期,然后月份部分日期,然后我需要第三栏作为月份年。
这意味着,在运行查询时,我应该有三列:
如果我的日期是2015年9月11日
当我运行这个查询时,结果应该如下所示:
Year Month YearMonth
2015 09 09-2015 但是,当我运行查询时,我会得到错误:
Msg 207, Level 16, State 1, Line 6
Invalid column name 'month'.
Msg 207, Level 16, State 1, Line 6
Invalid column name 'year'. 我使用以下查询获得正确的结果:
select distinct datepart(yy, a.date_created) as year, datepart(mm, a.date_created) as month, concat(datepart(mm, a.date_created), '-', datepart(yy, a.date_created)) as monthyr
from dbo.assignment a 我想在连接时避免再次使用datepart。所以,我试着做一些类似于第一次查询的事情。
还有其他方法可以达到同样的效果吗?
谢谢
发布于 2015-09-11 19:12:07
要删除重复表达式,可以使用派生查询(select .. from select ..)。否则,不可能访问在同一select中select输出子句中引入的标识符。
但是,Server应该同样优化这两个表达式,并消除“重复”表达式。我相当肯定,即使有不同的移动,它也会产生相同的计划--但是请看实际的查询计划来确定。
带有派生选择的查询可能如下所示:
select
year, month, concat(month, '-', year) as monthyr
from (
select distinct
datepart(yy, a.date_created) as year,
datepart(mm, a.date_created) as month
from dbo.assignment a
) t虽然在某些情况下这会导致更清晰的查询,但最大的改进可能是添加新行和缩进。
发布于 2015-09-11 19:18:54
子查询的效率会略高一点:
select *,concat(month, '-', year) as monthyr
from (
select distinct datepart(yy, date_created) as year
, datepart(mm, date_created) as month
from dbo.assignment) ahttps://stackoverflow.com/questions/32530489
复制相似问题