获取查询中每个分区的连续编号

时间:2017-11-11 08:57:57

标签: sql sql-server tsql

我有这张表(示例数据):

CREATE TABLE A
    ([Idx] int, [Title] varchar(50), [Sort] int)
;    
INSERT INTO A
    ([Idx], [Title], [Sort])
VALUES    
    (6, 'b', 1),
    (6, 'b', 2),    
    (6, 'b', 3),

    (4, 'a', 4),
    (4, 'a', 5),    
    (4, 'a', 6),

    (7, 'c', 7),
    (7, 'c', 8),    
    (7, 'c', 9)
;

我的查询:

SELECT * 
FROM A
ORDER BY Sort

结果:

| Idx | Title | Sort |
|-----|-------|------|
|   6 |     b |    1 |
|   6 |     b |    2 |
|   6 |     b |    3 |
|   4 |     a |    4 |
|   4 |     a |    5 |
|   4 |     a |    6 |
|   7 |     c |    7 |
|   7 |     c |    8 |
|   7 |     c |    9 |

我想从查询中的每个分区获得从1开始的连续编号。 (分区是Idx

预期结果:

| Idx | Title | Sort | N |
|-----|-------|------|---|
|   6 |     b |    1 | 1 |
|   6 |     b |    2 | 1 |
|   6 |     b |    3 | 1 |

|   4 |     a |    4 | 2 |
|   4 |     a |    5 | 2 |
|   4 |     a |    6 | 2 |

|   7 |     c |    7 | 3 |
|   7 |     c |    8 | 3 |
|   7 |     c |    9 | 3 |

如果可能,最好使用? OVER (PARTITION BY Idx ORDER BY Sort) 我还必须保持Sort订单!

3 个答案:

答案 0 :(得分:1)

您可以使用DENSE_RANK()功能

SELECT *, DENSE_RANK() OVER (ORDER BY Title) N FROM <table_name>

结果:

Idx Title Sort  N
6   a     1     1
6   a     2     1
6   a     3     1
4   b     4     2
4   b     5     2
4   b     6     2
7   c     7     3
7   c     8     3
7   c     9     3

答案 1 :(得分:1)

我想如果您不想使用DENSE_RANK(),您可以执行以下操作:

select A.*, B.GRP from A
INNER JOIN (
select row_number() over(order by srt) GRP,idx
FROM ( select  idx,MIN(sort) srt from A group by idx) t1 ) B
on A.Idx = B.idx
order by sort

答案 2 :(得分:0)

;with cte
as
(
select *, row_number()over ( order by idx ) as rwnum,DENSE_RANK() over (Order  by title) as rank 
 from #a 

)

,cte3
as
(
select c.Idx as idx1,c.Title as title1,c.sort as sort1,c.rwnum,c.rank ,a.Idx ,a.Sort,a.Title
from
cte as c 
join #A as a on c.rwnum=a.sort
)

select idx,Title,Sort,rank from cte3