SQL错误为DATEPART()或YEAR()创建别名

时间:2017-11-04 17:49:35

标签: sql sql-server tsql

是否有人知道为什么在尝试为DATEPART()或YEAR()创建别名时可能会出错?

为了运行查询,我必须输入整个DATEPART()函数(如果尝试使用YEAR()则会出现相同的错误:

SELECT TOP 3 ShipCountry,DATEPART(year,orderdate), AvgFreight=AVG(freight)
FROM orders
WHERE DATEPART(year,orderdate)='2015' 
Group by ShipCountry, DATEPART(year,orderdate)
Order by AvgFreight desc

我试着这样做:

SELECT TOP 3 ShipCountry,OrdersByYear=DATEPART(year,orderdate), AvgFreight=AVG(freight)
FROM orders
WHERE OrdersByYear='2015' 
Group by ShipCountry, OrdersByYear
Order by AvgFreight desc

错误是:

  

消息207,级别16,状态1,行3无效的列名称' OrdersByYear'。   消息207,级别16,状态1,行4无效的列名称' OrdersByYear'。

没有AVG别名的错误,谢谢!

1 个答案:

答案 0 :(得分:1)

别名很好。你不能在GROUP BY

中使用别名
SELECT TOP 3 ShipCountry, DATEPART(year,orderdate) as orderyear,
       AVG(freight) as  AvgFreight
FROM orders
WHERE orderDate >= '2015-01-01' and orderDate < '2016-01-01'
Group by ShipCountry, DATEPART(year, orderdate)
Order by AvgFreight desc;

请注意,此查询的group by不需要它,因为您只查看一年:

select TOP 3 ShipCountry, max(datepart(year, orderdate)) as orderyear,
       AVG(freight) as  AvgFreight
from orders
where orderDate >= '2015-01-01' and orderDate < '2016-01-01'
Group by ShipCountry
Order by AvgFreight desc;

请注意,我更改了where子句中的日期比较。这使优化器更容易生成更好的查询计划。