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

求一条很难的sql语句,谢谢!
表内容如下
  NO                     Num
01050232             7
03039483             8
51050232             2
05939382             4
06938347             8
55939382             12

要按以下规则统计:满足No字段的前两位相差50,后面的位都相同的记录统计在一起。
如上面的记录,统计完了之后的结果如下:
  NO                     Num
**050232             9
**039483             8
**939382             16
**938347             8

请问这样的SQL语句应该怎么写?

------解决方案--------------------
create table #(NO bigint, Num int)
insert into # select 01050232 , 7
union all select 03039483 , 8
union all select 51050232 , 2
union all select 05939382 , 4
union all select 06938347 , 8
union all select 55939382 , 12

select '** '+cast(right(NO,6) as varchar),sum(Num) from # group by right(NO,6)


---
**039483 8
**050232 9
**938347 8
**939382 16
------解决方案--------------------
declare @t table(NO varchar(12),Num int)
insert into @t select '01050232 ',7
insert into @t select '03039483 ',8
insert into @t select '51050232 ',2
insert into @t select '05939382 ',4
insert into @t select '06938347 ',8
insert into @t select '55939382 ',12

select
NO,sum(Num) as Num
from
(select right( '00 '+rtrim(left(NO,2)%50),2)+stuff(NO,1,2, ' ') as No1,stuff(NO,1,2, '** ') as NO,Num from @t) t
group by
NO,NO1

/*
NO Num
------------ -----------
**050232 9
**039483 8
**939382 16
**938347 8
*/