我想在一个记录中插入一个page_number,该记录连续计算一列中的副本。示例输出:
ID PAGE_ORDER PAGE_NUMBER
1 7 1
2 7 1
3 7 1
4 7 1
5 7 1
6 10 2
7 10 2
8 10 2
9 10 2
10 10 2
11 13 3
12 13 3
13 13 3
14 13 3
15 13 3
16 9 4
17 9 4
18 9 4
19 9 4
20 9 4
21 16 5
22 16 5
23 16 5
24 16 5
25 16 5
26 11 6
27 11 6
28 11 6
29 11 6
30 11 6
31 12 7
32 12 7
33 12 7
34 12 7
35 12 7
36 4 8
37 4 8
38 4 8
39 4 8
40 4 8
41 5 9
42 5 9
43 5 9
44 5 9
45 5 9
46 14 10
47 14 10
48 14 10
49 14 10
50 14 10
51 15 11
52 15 11
53 15 11
54 15 11
55 15 11
56 6 12
57 6 12
58 6 12
59 6 12
60 6 12
61 1 13
62 1 13
63 1 13
64 1 13
65 1 13
66 2 14
67 2 14
68 2 14
69 2 14
70 2 14
71 8 15
72 8 15
73 8 15
74 8 15
75 8 15
76 3 16
77 3 16
78 3 16
79 3 16
80 3 16
如何像输出一样添加page_number
列?
page_number列的规则是基于page_order列中的重复记录连续计数。
请指教。谢谢。
答案 0 :(得分:1)
我在问题中找到了解决方案:
select *, dense_rank() over (order by sort)
from (select *, sort = min(ID) over (partition by page_order)
from #tbl) c
order by c.ID
感谢msdn论坛中的KH Tan。 http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/55a18861-50a1-4f8a-b6f7-16992fa51e94
谢谢你们!
答案 1 :(得分:0)
我不确定您的数据是如何排序的 - 似乎没有特定顺序的重复数据。
但是,如果您使用的是SQL Server 2005或2008,那么您的解决方案可能会涉及RANK
答案 2 :(得分:0)
我对ID
列如何处理有点不清楚,因为它始终是相同的值,但是根据您提供的数据,这应该为您提供所需的输出:
WITH Results AS (
SELECT
MAX(ID) as ID,
Page_Order,
ROW_NUMBER() OVER (ORDER BY Page_Order DESC) as Page_Number
FROM
PageNumberTable
GROUP BY
Page_Order
)
SELECT
Results.*
FROM
PageNumberTable
JOIN Results ON PageNumberTable.Page_Order = Results.Page_Order
答案 3 :(得分:0)
试试这个
SELECT id, page_order,
DENSE_RANK() OVER(ORDER BY
(MIN(id) OVER(PARTITION BY page_order)) as page_number
FROM table_name
ORDER BY id
编辑:试试这个
;WITH T1 AS
(
SELECT id, page_order, MIN(id) OVER(PARTITION BY page_order) AS min_id
)
SELECT id, page_order, DENSE_RANK() OVER(ORDER BY min_id) AS page_number
FROM T1
ORDER BY id