问题描述
|
我尝试运行以下查询:
select a,b,min(c) from tablename where e=1 and f=1 group by a,b order by a,c
但是得到了错误:
Column name \'tablename.c\' is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
但是c包含在聚合函数min()中,那么这里的问题是什么?有解决方法吗?
这是在sqlserver 2000上(使用sqlserver 2008管理控制台)。
解决方法
当您在该列上使用聚合时,不再是ѭ2\,而是\“ aggregated c \”,这就是为什么您不能在order by子句中使用它的原因。
您需要为该列添加别名以按以下顺序使用它
select a,b,min(c) as min_c from tablename where e=1 and f=1 group by a,b order by a,min_c
编辑:
为什么列c不可用?
在语句中使用子句group by时,我们将原始表i转换为新的临时表。
在您使用a列和b列进行分组的情况下,这些列中的数据将仅限于唯一性而不会更改。
在第2列上,您正在使用一个函数,该函数针对每个唯一组将检索c的最小值,为此,必须创建一个新列来存储该结果。
order by子句是在select部分执行的查询的最后一部分。因此,临时表的结果不是源表的结果。
语句执行的简单顺序如下:
FORM
JOIN
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
, 尝试这个
select * from
(
select a,min(c) as c from tablename where e=1 and f=1 group by a,b
) d order by a,c
, 尝试这个:
select a,min(c)
from tablename
where e=1 and f=1
group by a,b
order by a,min(c)
或这个:
select a,b
order by 1,2,3