您的位置:首页 > 其它

在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句

2011-12-03 10:14 309 查看
突然看到这个问题,脑袋一蒙,不知道啥意思,后来想想,试图把select里的选项放到后面,问题自然解决!

下面这个就是报“在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句”问题语句

select shipcountry,sum(shipvia) as totalvia,OrderDate as thefirsttime from orders group by shipcountry

下面是通过的,请注意orderdate

select shipcountry,sum(shipvia) as totalvia,OrderDate as thefirsttime from orders group by shipcountry,orderdate

相应的从网上看到其他的朋友也有这样的问题

比如要显示authors表中的au_fname,au_lname,zip, city,state信息,并且按city分组(相同city的排列在一起)

错误的表达:

select au_fname,au_lname,zip, city,state

from authors

group by city

就会出现:服务器: 消息 8120,级别 16,状态 1,行 1

列 'authors.au_fname' 在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

服务器: 消息 8120,级别 16,状态 1,行 1

列 'authors.au_lname' 在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

...... 的错误提示。

正确的表达:

select au_fname,au_lname,zip, city,state

from authors

group by city,au_lname,au_fname,zip,state

即指定 GROUP BY 时,选择列表中任一非聚合表达式内的所有列都应包含在 GROUP BY 列表中,或者 GROUP BY 表达式必须与选择列表表达式完全匹配。

其实还有更好的办法:

select au_fname,au_lname,zip, city,state

from authors

order by city

即使用order by 子句

还是authors表,要求在每个城市取一个作者,显示该作者的左右信息:

可以用如下表达:

select * from authors

where au_id in

(select min(au_id)

from authors

group by city)

其实是分组后取最小ID的

比如要显示authors表中的au_fname,au_lname,zip, city,state信息,并且按city分组(相同city的排列在一起)

错误的表达:

select au_fname,au_lname,zip, city,state

from authors

group by city

就会出现:服务器: 消息 8120,级别 16,状态 1,行 1

列 'authors.au_fname' 在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

服务器: 消息 8120,级别 16,状态 1,行 1

列 'authors.au_lname' 在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

...... 的错误提示。

正确的表达:

select au_fname,au_lname,zip, city,state

from authors

group by city,au_lname,au_fname,zip,state

即指定 GROUP BY 时,选择列表中任一非聚合表达式内的所有列都应包含在 GROUP BY 列表中,或者 GROUP BY 表达式必须与选择列表表达式完全匹配。

其实还有更好的办法:

select au_fname,au_lname,zip, city,state

from authors

order by city

即使用order by 子句

还是authors表,要求在每个城市取一个作者,显示该作者的左右信息:

可以用如下表达:

select * from authors

where au_id in

(select min(au_id)

from authors

group by city)

其实是分组后取最小ID的行

本文来自http://hi.baid
acef
u.com/%C5%A1%B0%CD%CD%C3/blog/item/e887a86e17594ed281cb4a9c.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  服务器 c
相关文章推荐