group by语句

突然看到这个问题,脑袋一蒙,不知道啥意思,后来想想,试图把select里的选项放到后面,问题自然解决!
 
下面这个就是报“在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在GROUP BY 子句”问题语句
select shipcountry,sum(shipvia) as totalvia,OrderDate asthefirsttime from orders group by shipcountry
 
下面是通过的,请注意orderdate
select shipcountry,sum(shipvia) as totalvia,OrderDate asthefirsttime 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的行

发布了8 篇原创文章 · 获赞 3 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章