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

gos_q 2007-01-20 03:02:45
有如下表

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

希望得到如下结果

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

我不知这个序号要怎样才可以select出来,大家帮下忙可以吗?
...全文
310 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
marco08 2007-01-20
  • 打赏
  • 举报
回复
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=(select count(distinct type) from T where type<=tmp.type), type, num=sum(num)
from T as tmp
group by type
order by type

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

(3 row(s) affected)
marco08 2007-01-20
  • 打赏
  • 举报
回复
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=(select count(distinct type)+1 from T where type<tmp.type), type, num=sum(num)
from T as tmp
group by type
order by type

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

(3 row(s) affected)
caixia615 2007-01-20
  • 打赏
  • 举报
回复
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 行)
marco08 2007-01-20
  • 打赏
  • 举报
回复

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)
gos_q 2007-01-20
  • 打赏
  • 举报
回复
谢谢两位,现在结贴.

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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