SQL 列在 ORDER BY 中无效,未包含在聚合或 GROUP BY 中

SQL Column is invalid in ORDER BY, not contained in aggregate or GROUP BY(SQL 列在 ORDER BY 中无效,未包含在聚合或 GROUP BY 中)
本文介绍了SQL 列在 ORDER BY 中无效,未包含在聚合或 GROUP BY 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

SELECT TOP 1 e.EmployeeID来自员工 eINNER JOIN 订单 o ON o.EmployeeID = e.EmployeeID内部联接 (选择订单 ID,SUM((UnitPrice * Quantity) - Discount) AS TotalOrderPriceFROM [订单详情]按订单 ID 分组) oi ON oi.OrderID = o.OrderIDGROUP BY e.employeeidORDER BY TotalOrderPrice * 0.1 DESC,COUNT(o.OrderID) ASC

<块引用>

消息 8127,级别 16,状态 1,第 11 行

列oi.TotalOrderPrice"在 ORDER BY 子句中无效,因为它不包含在聚合函数或 GROUP BY 子句中.

解决方案

如果你使用 GROUP BY,你只能SELECT(因此,ORDER) 列,它们是

  1. 您分组所依据的任一列
  2. 要么是聚合函数(例如,MAX()COUNT())

MySQL 没有这个限制,但它只是 SQL 标准的特定于 MySQL 的扩展.任何其他 SQL 服务器,包括 Microsoft SQL,都有这个.

SELECT TOP 1 e.EmployeeID
FROM Employees e
    INNER JOIN Orders o ON o.EMployeeID = e.EmployeeID
    INNER JOIN (
      SELECT OrderID,
             SUM((UnitPrice * Quantity) - Discount) AS TotalOrderPrice
      FROM [Order Details]
      GROUP BY OrderID
    ) oi ON oi.OrderID = o.OrderID
GROUP BY e.employeeid
ORDER BY TotalOrderPrice * 0.1 DESC,
         COUNT(o.OrderID) ASC

Msg 8127, Level 16, State 1, Line 11

Column "oi.TotalOrderPrice" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

解决方案

If you use a GROUP BY, you can only SELECT (and thus, ORDER) the columns, which are

  1. Either one of the columns you grouped by with
  2. Either is an aggregate function (for example, MAX() or COUNT())

MySQL hasn't this limitation, but it is only a MySQL-specific extension to the SQL standard. Any other SQL server, included the Microsoft SQL, have this.

这篇关于SQL 列在 ORDER BY 中无效,未包含在聚合或 GROUP BY 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)