提问:SQL查询,将字段1分组且只显示 最小的字段2

weixin_41831497 2018-03-23 10:08:43
现在有一张表A:
colum1 colum2
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

现在想要查询出的结果是:
colum1 colum2
1 1
2 1
3 1

查询思想:
只留下 colum2 最小的 colum1分类汇总行

求大神

...全文
791 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
二月十六 2018-03-28
  • 打赏
  • 举报
回复
引用 4 楼 weixin_41831497 的回复:
[quote=引用 1 楼 sinat_28984567 的回复:]
--测试数据
if not object_id(N'Tempdb..#A') is null
	drop table #A
Go
Create table #A([colum1] int,[colum2] int)
Insert #A
select 1,1 union all
select 1,2 union all
select 1,3 union all
select 2,1 union all
select 2,2 union all
select 2,3 union all
select 3,1 union all
select 3,2 union all
select 3,3
Go
--测试数据结束
Select [colum1],MIN([colum2]) AS [colum2] from #A GROUP BY [colum1]
若要取出所有字段,怎么破?这个得不到 所有字段 [/quote] 去所有字段什么意思? 直接
select * from 表
不就是了么
weixin_41831497 2018-03-28
  • 打赏
  • 举报
回复
引用 1 楼 sinat_28984567 的回复:
--测试数据
if not object_id(N'Tempdb..#A') is null
	drop table #A
Go
Create table #A([colum1] int,[colum2] int)
Insert #A
select 1,1 union all
select 1,2 union all
select 1,3 union all
select 2,1 union all
select 2,2 union all
select 2,3 union all
select 3,1 union all
select 3,2 union all
select 3,3
Go
--测试数据结束
Select [colum1],MIN([colum2]) AS [colum2] from #A GROUP BY [colum1]
若要取出所有字段,怎么破?这个得不到 所有字段
中国风 2018-03-23
  • 打赏
  • 举报
回复
效率上考虑,如上:只有两列时用#1,有多列取最小值行时用#2
中国风 2018-03-23
  • 打赏
  • 举报
回复
或 e.g.
SELECT * FROM (SELECT *,ROW_NUMBER()OVER(PARTITION BY colum1 ORDER BY colum2) AS RN FROM tablename) AS T WHERE RN=1
二月十六 2018-03-23
  • 打赏
  • 举报
回复
--测试数据
if not object_id(N'Tempdb..#A') is null
drop table #A
Go
Create table #A([colum1] int,[colum2] int)
Insert #A
select 1,1 union all
select 1,2 union all
select 1,3 union all
select 2,1 union all
select 2,2 union all
select 2,3 union all
select 3,1 union all
select 3,2 union all
select 3,3
Go
--测试数据结束
Select [colum1],MIN([colum2]) AS [colum2] from #A GROUP BY [colum1]


590

社区成员

发帖
与我相关
我的任务
社区描述
提出问题
其他 技术论坛(原bbs)
社区管理员
  • community_281
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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