sql语句中group by,聚合函数的使用。单行子查询返回多行怎么办?求解答!

select max(caption) from table group by id这条sql帮我筛选出了77条(ID不同,并且ID相同中caption最大的数据)。我想查出这77条全部列。
select * from table where caption = (select max(caption) from table group by id)这样做会报错。distinct(id)一共有77条数据。请大神们指教!

两个办法。
(1)联合查询(oracle写法,如为其他数据库自行修改,这里只提供思路)
select table.id,table.XXXXX,table.XXXXX,table.caption,table.XXXXX from table,(select id,max(caption) max_cap from table group by id) b where table.id=b.id and table.caption=b.max_cap
(2)组合查询
select * from table where id||'_'||caption in (select id||'_'||max(caption) max_cap from table group by id)
加_是为了方防止出现特殊情况,比如id=1,caption=130 和id=11,caption=30的情况出现
不知道你是什么数据库,||是Oracle的连接符,用于连接字符串,其他数据库应该也有类似的东西,这个就自己掌握吧
温馨提示:内容为网友见解,仅供参考
第1个回答  2019-07-30
group by函数,允许查询出多列,你的sql语句中直接把多列都列出来就可以了
比如你的列有id,name,type,caption都想列出来,则
select id,name,type,max(caption) from table group by id

如果同一id下,你还想在想看某一类别下最大caption的数据,则group by 后面增加type就行了

select id,name,type,max(caption) from table group by id,type追问

你说的是这样的吗?这样的话两次结果条数是不一样的。应该只能查到777条数据的。

追答

我晕,前面那个sql语句,是你这道题的答案,后面那个,我的意识是,如果你还需要,对其他列,继续进行分组,就会用到

你第一个图,第二个sql语句。group by后面,只写id,不要写别的

本回答被网友采纳
第2个回答  2019-07-30
把 where后面的caption=(select***)改为 caption in 就好了
-----
试下这个看看select * from table where caption = (select max(caption) from table group by id)把这个改成 select a.* from table a,(select max(caption),id from table group by id) b where a.id=b.id
第3个回答  2019-07-31
select * from table where id = select id from(select id,max(caption) from table group by id)
这个意思么
第4个回答  2019-07-30
你没有select id ,为什么还要对id使用聚合函数追问

本来查(select max(caption) from MOS_SCSDATA_DETAIL_INFO group by id) 有77条数据,都展开的话有7200多条

追答

select id,max(caption)group by id有77条,加了字段变成select id,字段1,max(caption)group by id,字段1,结果会增加?

追问

恩恩 是的。你看下这两条sql的结果

追答

这说明在id,caption都确定的情况下其他字段还有重复值?如果是这样你之前的查法也是不会只有77条数据吧,都会列出来的

相似回答