问一个SELECT 的问题

stevenhzhang 2012-03-21 02:14:30
有一个表格

id ord_id
1 10
2 10
3 20
4 20
5 20

现在想生成一个新表格,多一个列new_id,要求是:显示一样的ord_id里取最小的id

id new_id ord_id
1 1 10
2 1 10
3 3 20
4 3 20
5 3 20
...全文
62 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

--> 测试数据:[t1]
if object_id('[t1]') is not null drop table [t1]
create table [t1]([id] int,[ord_id] int)
insert [t1]
select 1,10 union all
select 2,10 union all
select 3,20 union all
select 4,20 union all
select 5,20

select id,(select min(id) from t1 a where a.[ord_id]=b.[ord_id])
as [newid] ,[ord_id] from t1 b
group by [ord_id],id
/*
id newid ord_id
1 1 10
2 1 10
3 3 20
4 3 20
5 3 20
*/

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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