首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求分组后有自动分组序号的写法解决办法

2012-03-14 
求分组后有自动分组序号的写法有如下表类型数量B3A2C6B4希望得到如下结果序号类型数量1A22B73C6我不知这个

求分组后有自动分组序号的写法
有如下表

类型     数量
B           3
A           2
C           6
B           4

希望得到如下结果

序号   类型   数量
1         A         2
2         B         7
3         C         6

我不知这个序号要怎样才可以select出来,大家帮下忙可以吗?

[解决办法]

create table T(type varchar(10), num int)
insert T select 'B ', 3
union all select 'A ', 2
union all select 'C ', 6
union all select 'B ', 4

select ID=identity(int, 1, 1), type, num=sum(num)
into #T
from T
group by type
order by type

select * from #T

--result
ID type num
----------- ---------- -----------
1 A 2
2 B 7
3 C 6

(3 row(s) affected)

[解决办法]
declare @a table(a char(10),b int)
insert into @a select 'B ',3
union all select 'A ',2
union all select 'C ',6
union all select 'B ',4

select c=(select count(*) from (select distinct a from @a) a where b.a> =a.a ),a ,sum(B)AS B FROM @A b group by a
result:
c a B
----------- ---------- -----------
1 A 2
2 B 7
3 C 6

(所影响的行数为 3 行)

热点排行