2017-11-11 71 views
1

我有此表(樣品數據):獲得的連續數爲每個分區在查詢

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的順序!

回答

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 
+0

我不能使用DENSE_RANK()b/c它給出了錯誤的結果。 – zig

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 
+0

那是我第一件事測試。 'DENSE_RANK()超過(由Idx ORDER BY分區劃分)AS rnk'不起作用。 – zig

+0

@zig你檢查過上面的查詢,或者只是刪除'(PARTITION BY Idx)'? –

+0

我還必須維護'排序'順序。抱歉,我在編輯的問題中沒有說清楚。 – zig

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