Noob关注:T-SQL Group By Clause错误

时间:2011-11-13 22:27:39

标签: sql sql-server tsql

我不确定我做错了什么。这是我正在阅读的T-SQL Fundamentals书中的示例查询...

SELECT empid, orderdate FROM Sales.Orders
WHERE custid = 71
GROUP BY empid, YEAR(orderdate)

我收到以下错误:

  

Msg 8120,Level 16,State 1,Line 1列'Sales.Orders.orderdate'是   在选择列表中无效,因为它不包含在任何一个中   聚合函数或GROUP BY子句。

我做错了什么?...

3 个答案:

答案 0 :(得分:2)

您提供的GROUP BY正在处理empid和订单日期(INT)。但是SELECT正在返回empid和DATETIME数据类型......忽略数据类型,数据在被分组的内容和数据类型之间是不同的。呈现。

您需要使用:

  SELECT o.empid, 
         YEAR(o.orderdate) 
    FROM Sales.Orders o
   WHERE o.custid = 71
GROUP BY o.empid, YEAR(o.orderdate)

......或:

  SELECT o.empid, 
         o.orderdate 
    FROM Sales.Orders o
   WHERE o.custid = 71
GROUP BY o.empid, o.orderdate

或者,SQL Server允许您在GROUP BY中引用列别名:

  SELECT o.empid, 
         YEAR(o.orderdate) AS yr
    FROM Sales.Orders o
   WHERE o.custid = 71
GROUP BY o.empid, yr

答案 1 :(得分:1)

试试这个 -

SELECT empid, YEAR(orderdate) FROM Sales.Orders
WHERE custid = 71
GROUP BY empid, YEAR(orderdate)

有一篇优秀的博客文章解释了您收到的错误以及您收到错误的原因 - http://weblogs.sqlteam.com/jeffs/archive/2007/07/20/but-why-must-that-column-be-contained-in-an-aggregate.aspx

答案 2 :(得分:0)

尝试类似的东西

SELECT * FROM Sales.Orders AS o
WHERE custid = 71
GROUP BY YEAR(o.orderdate)