是否可以使用SQL向GROUP BY添加标识?

时间:2010-01-14 17:38:01

标签: sql sql-server tsql row-number

是否可以向GROUP BY添加标识列,以便每个副本都有一个标识号?

我的原始数据如下:

1    AAA  [timestamp]
2    AAA  [timestamp]
3    BBB  [timestamp]
4    CCC  [timestamp]
5    CCC  [timestamp]
6    CCC  [timestamp]
7    DDD  [timestamp]
8    DDD  [timestamp]
9    EEE  [timestamp]
....

我想将其转换为:

1    AAA   1
2    AAA   2
4    CCC   1
5    CCC   2
6    CCC   3
7    DDD   1
8    DDD   2
...

解决方案是:

CREATE PROCEDURE [dbo].[RankIt]
AS
BEGIN
SET NOCOUNT ON;

SELECT  *, RANK() OVER(PARTITION BY col2 ORDER BY timestamp DESC) AS ranking 
FROM MYTABLE;

END

2 个答案:

答案 0 :(得分:5)

如果您使用的是Sql Server 2005,则可以尝试使用ROW_NUMBER

DECLARE @Table TABLE(
        ID INT,
        Val VARCHAR(10)
)

INSERT INTO @Table SELECT 1,'AAA'
INSERT INTO @Table SELECT 2,'AAA'
INSERT INTO @Table SELECT 3,'BBB' 
INSERT INTO @Table SELECT 4,'CCC' 
INSERT INTO @Table SELECT 5,'CCC' 
INSERT INTO @Table SELECT 6,'CCC' 
INSERT INTO @Table SELECT 7,'DDD' 
INSERT INTO @Table SELECT 8,'DDD' 
INSERT INTO @Table SELECT 9,'EEE' 

SELECT  *,
        ROW_NUMBER() OVER(PARTITION BY VAL ORDER BY Val)
FROM    @Table

答案 1 :(得分:3)

create table #testalot
(
  [id] int identity,
  data varchar(50)
)

insert #testalot (data) values('AAA')
insert #testalot (data) values('AAA')
insert #testalot (data) values('BBB')
insert #testalot (data) values('CCC')
insert #testalot (data) values('CCC')
insert #testalot (data) values('CCC')
insert #testalot (data) values('DDD')
insert #testalot (data) values('DDD')

select *,ROW_NUMBER() OVER(PARTITION BY data ORDER BY data DESC) AS 'Number'
 from #testalot

 drop table #testalot

返回

id  data Number
1   AAA  1
2   AAA  2
3   BBB  1
4   CCC  1
5   CCC  2
6   CCC  3
7   DDD  1
8   DDD  2