我想用rowcount对我的表数据进行分组。按日期为每个ProductID排序的前12行将获得值= 1.接下来的12行将获得值= 2,等等。
表结构如何显示:
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
答案 0 :(得分:1)
使用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