基于行数排名 SQL Server 2008 R2
Rank based on row number SQL Server 2008 R2
我想按行数对我的 table 数据进行分组排名。每个 ProductID 按日期排序的前 12 行将获得值 = 1。接下来的 12 行将获得值 = 2,依此类推。
table 结构看起来如何:
For ProductID = 1267 are below associated dates:
02-01-2016
03-01-2016
.
. (skipping months..table has one date per month)
.
12-01-2016
02-01-2017
.
.
.
02-01-2018
使用 row_number() over()
和一些算法来计算按日期排序的 12 组(每个 productid)。将排序更改为 ASCendng 或 DESCendng 以满足您的需要。
select *
, (11 + row_number() over(partition by productid order by somedate DESC)) / 12 as rnk
from mytable
GO
myTableID | productid | somedate | rnk
--------: | :------------- | :------------------ | :--
9 | 123456 | 2018-11-12 08:24:25 | 1
8 | 123456 | 2018-10-02 12:29:04 | 1
7 | 123456 | 2018-09-09 02:39:30 | 1
2 | 123456 | 2018-09-02 08:49:37 | 1
1 | 123456 | 2018-07-04 12:25:06 | 1
5 | 123456 | 2018-06-06 11:38:50 | 1
12 | 123456 | 2018-05-23 21:12:03 | 1
18 | 123456 | 2018-04-02 03:59:16 | 1
3 | 123456 | 2018-01-02 03:42:24 | 1
17 | 123456 | 2017-11-29 03:19:32 | 1
10 | 123456 | 2017-11-10 00:45:41 | 1
13 | 123456 | 2017-11-05 09:53:38 | 1
16 | 123456 | 2017-10-20 15:39:42 | 2
4 | 123456 | 2017-10-14 19:25:30 | 2
20 | 123456 | 2017-09-21 21:31:06 | 2
6 | 123456 | 2017-04-06 22:10:58 | 2
14 | 123456 | 2017-03-24 23:35:52 | 2
19 | 123456 | 2017-01-22 05:07:23 | 2
11 | 123456 | 2016-12-13 19:17:08 | 2
15 | 123456 | 2016-12-02 03:22:32 | 2
dbfiddle here
我想按行数对我的 table 数据进行分组排名。每个 ProductID 按日期排序的前 12 行将获得值 = 1。接下来的 12 行将获得值 = 2,依此类推。
table 结构看起来如何:
For ProductID = 1267 are below associated dates:
02-01-2016
03-01-2016
.
. (skipping months..table has one date per month)
.
12-01-2016
02-01-2017
.
.
.
02-01-2018
使用 row_number() over()
和一些算法来计算按日期排序的 12 组(每个 productid)。将排序更改为 ASCendng 或 DESCendng 以满足您的需要。
select * , (11 + row_number() over(partition by productid order by somedate DESC)) / 12 as rnk from mytable GO
myTableID | productid | somedate | rnk --------: | :------------- | :------------------ | :-- 9 | 123456 | 2018-11-12 08:24:25 | 1 8 | 123456 | 2018-10-02 12:29:04 | 1 7 | 123456 | 2018-09-09 02:39:30 | 1 2 | 123456 | 2018-09-02 08:49:37 | 1 1 | 123456 | 2018-07-04 12:25:06 | 1 5 | 123456 | 2018-06-06 11:38:50 | 1 12 | 123456 | 2018-05-23 21:12:03 | 1 18 | 123456 | 2018-04-02 03:59:16 | 1 3 | 123456 | 2018-01-02 03:42:24 | 1 17 | 123456 | 2017-11-29 03:19:32 | 1 10 | 123456 | 2017-11-10 00:45:41 | 1 13 | 123456 | 2017-11-05 09:53:38 | 1 16 | 123456 | 2017-10-20 15:39:42 | 2 4 | 123456 | 2017-10-14 19:25:30 | 2 20 | 123456 | 2017-09-21 21:31:06 | 2 6 | 123456 | 2017-04-06 22:10:58 | 2 14 | 123456 | 2017-03-24 23:35:52 | 2 19 | 123456 | 2017-01-22 05:07:23 | 2 11 | 123456 | 2016-12-13 19:17:08 | 2 15 | 123456 | 2016-12-02 03:22:32 | 2
dbfiddle here