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

用sql实现一个思路 ---在线期求!!!!
例如有一个表M   有A   B   C三列,其中值为
  A       B       C
  a1     b1     c1
  a1     b1     c2
  a1     b2     c1
  a2     b2     c2
  a2     b2     c3
  a1     b2     c4
  要求将其数据以A   ,B列作为分组条件保存在别一个表N中,并区分不同组的明细资料(如加个区分列D)具体形式如下:
    A     B         C       D
  a1     b1     c1       1
  a1     b1     c2       1
  a1     b2     c1       2  
  a2     b2     c2       3  
  a2     b2     c3       3
  a1     b2     c4       2
帮忙想一下写法,想两天啦,还是搞不定,谢谢大家啦!


------解决方案--------------------
select d = identity(int,1,1) , * into temp from m

select m.*,temp.d from m,temp where m.a = temp.a and m.b = temp.b
------解决方案--------------------
declare @a table(A varchar(10), B varchar(10), C varchar(10))
insert @a select 'a1 ', 'b1 ', 'c1 '
union all select 'a1 ', 'b1 ', 'c2 '
union all select 'a1 ', 'b2 ', 'c1 '
union all select 'a2 ', 'b2 ', 'c2 '
union all select 'a2 ', 'b2 ', 'c3 '
union all select 'a1 ', 'b2 ' , 'c4 '


select a,b,id=identity(int,1,1) into # from @a group by a,b
select a.*,b.id from @a a Inner join # b on a.a=b.a and a.b=b.b
drop table #

--result
/*
A B C id
---------- ---------- ---------- -----------
a1 b1 c1 1
a1 b1 c2 1
a1 b2 c1 2
a2 b2 c2 3
a2 b2 c3 3
a1 b2 c4 2

(所影响的行数为 6 行)
*/
------解决方案--------------------
create table m(A varchar(10),B varchar(10),C varchar(10))
insert into m values( 'a1 ', 'b1 ', 'c1 ')
insert into m values( 'a1 ', 'b1 ', 'c2 ')
insert into m values( 'a1 ', 'b2 ', 'c1 ')
insert into m values( 'a2 ', 'b2 ', 'c2 ')
insert into m values( 'a2 ', 'b2 ', 'c3 ')
insert into m values( 'a1 ', 'b2 ', 'c4 ')
go
select d = identity(int,1,1) , * into temp from (select distinct a,b from m) t
select m.*,temp.d from m,temp where m.a = temp.a and m.b = temp.b
drop table m,temp
/*
A B C d
---------- ---------- ---------- -----------
a1 b1 c1 1
a1 b1 c2 1
a1 b2 c1 2
a2 b2 c2 3
a2 b2 c3 3
a1 b2 c4 2

(所影响的行数为 6 行)

*/
------解决方案--------------------
declare @M table(A varchar(4),B varchar(4),C varchar(4))
insert into @M select 'a1 ', 'b1 ', 'c1 '
insert into @M select 'a1 ', 'b1 ', 'c2