关于SQL查询的问题

来源:百度知道 编辑:UC知道 时间:2024/05/10 21:47:49
有原始数据为:
id kind
--------
1 a
2 a
3 a
4 a
5 b
6 c
7 c

查询后作为一个新建表的结果为:
id kind count
---------------
1 a 3
2 b 1
3 c 2

给出完整查询语句啊..

自动编号用SQL实现比较困难,你的要求可以用下面实现:

create temp table t123 //---创建临时表---
(
item serial, //---序号类型(不同的数据库,这个类型写法不同)---
kind char(20),
count smallint
)

insert into t123(kind,count)
select kind,count(*) from table_name group by kind

你也可以将上面的数据取出的时候,给其赋一个自己增加的id.

希望对你有帮助。

--测试数据
declare @tb table(id int, kind varchar(10))
insert into @tb select 1,'a'
insert into @tb select 2,'a'
insert into @tb select 3,'a'
insert into @tb select 4,'a'
insert into @tb select 5,'b'
insert into @tb select 6,'c'
insert into @tb select 7,'c'

--查询
select
orderid=isnull((select count(1) from (select kind,count=count(kind) from @tb group by kind ) y where y.kind<x.kind),0) +1,
kind,
count
from
(
select kind,count=count(kind) from @tb group by kind
) x

--结果<