日期:2014-05-18  浏览次数:20510 次

问一个SELECT 的问题
有一个表格

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

------解决方案--------------------
SQL code

--> 测试数据:[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
*/