SQL组日期作为一个修订历史/批处理?

时间:2015-10-08 18:43:29

标签: sql-server

这是我的起点

+--------+---------+-------+------------+<br>
|  make  |  model  | Class |    Date    |<br>
+--------+---------+-------+------------+<br>
| honda  | accord  |     1 | 2015070169 |<br>
| honda  | civic   |     2 | 2015070169 |<br>
| honda  | fit     |     3 | 2015070169 |<br>
| toyota | camry   |     1 | 2015080954 |<br>
| BMW    | 7Series |     1 | 2015080959 |<br>
| BMW    | 5series |     2 | 2015080959 |<br>
| BMW    | 3Series |     3 | 2015080959 |<br>
+--------+---------+-------+------------+<br>

根据上表,日期已经做好了分组。但是,如果这些日期是像批次那样批量订购的话,那将会更容易。

+--------+---------+-------+------------+---------+<br>
|  make  |  model  | Class |    Date    | History |<br>
+--------+---------+-------+------------+---------+<br>
| honda  | accord  |     1 | 2015070169 |       1 |<br>
| honda  | civic   |     2 | 2015070169 |       1 |<br>
| honda  | fit     |     3 | 2015070169 |       1 |<br>
| toyota | camry   |     1 | 2015080954 |       2 |<br>
| BMW    | 7Series |     1 | 2015080959 |       3 |<br>
| BMW    | 5series |     2 | 2015080959 |       3 |<br>
| BMW    | 3Series |     3 | 2015080959 |       3 |<br>
+--------+---------+-------+------------+---------+<br>

我最接近目标的是使用此SQL查询

select make, model, class, date, 
,ROW_NUMBER() OVER (partition by class order by date) AS HISTORY
from table1
order by date

这是上述查询的结果

+--------+---------+-------+------------+---------+<br>
|  make  |  model  | Class |    Date    | History |<br>
+--------+---------+-------+------------+---------+<br>
| honda  | accord  |     1 | 2015070169 |       1 |<br>
| honda  | civic   |     2 | 2015070169 |       1 |<br>
| honda  | fit     |     3 | 2015070169 |       1 |<br>
| toyota | camry   |     1 | 2015080954 |       2 |<br>
| BMW    | 7Series |     1 | 2015080959 |       3 |<br>
| BMW    | 5series |     2 | 2015080959 |       2 |<br>
| BMW    | 3Series |     3 | 2015080959 |       2 |<br>
+--------+---------+-------+------------+---------+<br>
<br>

但它仍然不是我想要的。因为我按类分区,因此第1类有历史1,2和3,而另一类只有1和2。

实现这一目标的更好方法是什么。

1 个答案:

答案 0 :(得分:0)

使用DENSE_RANK()(按日期排序)根据日期给出数字。

select make, model, class, date
,DENSE_RANK() OVER (order by [date] ASC) AS HISTORY
from table1
order by date

ROW_NUMBER() - 为每一行指定一个唯一编号。该号码在分区中是唯一的。

RANK() - 为每行指定一个数字,但如果值相同,则会得到相同的数字。数字由有多少人排名分开。例如:1,1,3,3

DENSE_RANK() - 与排名相同,但数字更接近。例如:1,1,2,2