sql分组后查询每个分组的最小值的一条记录(mysql)

半吊子攻城狮 2017-01-09 10:52:28
表结构 如下:

期望结果:


解释:根据gid 进行分组 查询每个gid分组下price最小值的** 一行记录**(即对应pid主键的一整条记录) sql怎么写
...全文
3239 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
select * from tb tb1 where not exists(select 1 from tb tb2 where tb1.gid=tb2.gid and tb1.price<tb2.price)
Abeta 2017-04-16
  • 打赏
  • 举报
回复
如果price最小值都只存在1行,可以这样:
select t1.pid,t2.gid,t2.price,t1.other from
(select gid,min(price) price from t1 group by gid) t2
left join t1 on t1.gid=t2.gid and t1.price=t2.price
solofen 2017-04-15
  • 打赏
  • 举报
回复
SELECT * FROM (SELECT * FROM tab ORDER BY price) t GROUP BY t.gid;
中国风 2017-01-09
  • 打赏
  • 举报
回复

select * from (select *,@id:=if(`c_ID`=@gid,@id+1,1) as RN,@gid:=`gid` from table1 order by `gid`,`price`,`pid`) as t where RN=1 ;
半吊子攻城狮 2017-01-09
  • 打赏
  • 举报
回复
建表语句如下: CREATE TABLE `test` ( `pid` int(10) NOT NULL AUTO_INCREMENT, `gid` int(11) NOT NULL, `price` decimal(10,3) NOT NULL, `other` decimal(10,3) NOT NULL, PRIMARY KEY (`pid`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧