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

下面这个就是报“在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 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的行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值