按日期枚举记录

时间:2017-03-08 16:29:11

标签: sql sql-server

假设我们在特定日期销售的商品有5条记录

Date of Purchase             Qty
2016-11-29 19:33:50.000       5
2017-01-03 20:09:49.000       4
2017-02-23 16:21:21.000       11
2016-11-29 14:33:51.000       2
2016-12-02 16:24:29.000       4

我希望按日期按顺序枚举每条记录,并添加如下额外列:

Date of Purchase             Qty      Order
2016-11-29 19:33:50.000       5         1
2017-01-03 20:09:49.000       4         3
2017-02-23 16:21:21.000       11        4
2016-11-29 14:33:51.000       2         1
2016-12-02 16:24:29.000       4         2

请注意2016-11-29的两个日期如何具有相同的订单号,因为我只想按日期而不是按日期时间订购记录。我如何在纯SQL中创建这个额外的列?

1 个答案:

答案 0 :(得分:4)

使用dense_rank()并按date

DateOfPurchase排序
select * 
  , [Order] = dense_rank() over (order by convert(date,DateOfPurchase))
from t

rextester演示:http://rextester.com/FAAQL92440

返回:

+---------------------+-----+-------+
|   DateOfPurchase    | Qty | Order |
+---------------------+-----+-------+
| 2016-11-29 19:33:50 |   5 |     1 |
| 2016-11-29 14:33:51 |   2 |     1 |
| 2016-12-02 16:24:29 |   4 |     2 |
| 2017-01-03 20:09:49 |   4 |     3 |
| 2017-02-23 16:21:21 |  11 |     4 |
+---------------------+-----+-------+