1

我有一个包含第 1 组、第 2 组和日期字段的表格。

如果我运行此查询,我会得到以下结果:

SELECT 
   [group1]
  ,[group2]
  ,[date]
  ,ROW_NUMBER() over (PARTITION by [group1] order by [date]) as ord
FROM [dev_DP].[dbo].[myTable]

+--------+--------+-------------------------+-----+
| group1 | group2 |          date           | ord |
+--------+--------+-------------------------+-----+
| dan    | alarm  | 2014-05-14 12:00:00.000 |   1 |
| dan    | snooze | 2014-05-14 12:30:00.000 |   2 |
| dan    | snooze | 2014-05-14 12:50:00.000 |   3 |
| jim    | snooze | 2014-05-14 11:00:00.000 |   1 |
| jim    | snooze | 2014-05-14 12:45:00.000 |   2 |
| jim    | alarm  | 2014-05-14 13:45:00.000 |   3 |
+--------+--------+-------------------------+-----+

我想添加另一列,然后根据第 1 组和第 2 组字段向表中添加行号,但仅为第 1 组保留日期顺序。我想要的结果如下:

+--------+--------+---------------------+-----+------+
| group1 | group2 |        date         | ord | ord2 |
+--------+--------+---------------------+-----+------+
| dan    | alarm  | 2014-05-14 12:00:00 |   1 |    1 |
| dan    | snooze | 2014-05-14 12:30:00 |   2 |    1 |
| dan    | snooze | 2014-05-14 12:50:00 |   3 |    2 |
| jim    | snooze | 2014-05-14 11:00:00 |   1 |    1 |
| jim    | snooze | 2014-05-14 12:45:00 |   2 |    2 |
| jim    | alarm  | 2014-05-14 13:45:00 |   3 |    1 |
+--------+--------+---------------------+-----+------+

我怎样才能做到这一点?

谢谢丹

4

2 回答 2

1
  SELECT 
  [group1]
  ,[group2]
  ,[date]
  ,ROW_NUMBER() over (PARTITION by [group1] order by [date]) as ord1
  ,ROW_NUMBER() over (PARTITION by [group1], [group2] order by [date]) as ord2
  FROM [dev_DP].[dbo].[myTable]
于 2014-05-15T20:34:24.950 回答
0

如果我改变这些条款:

  SELECT 
  [group1]
  ,[group2]
  ,[date]

  ,ROW_NUMBER() over (PARTITION by [group1], [group2] order by [date]) as ord2
  ,ROW_NUMBER() over (PARTITION by [group1] order by [date]) as ord1
  FROM [dev_DP].[dbo].[myTable]

我认为这给了我想要的结果,但它没有......如果我添加另一条记录,您会看到错误。

+--------+--------+-------------------------+------+------+
| group1 | group2 |          date           | ord2 | ord1 |
+--------+--------+-------------------------+------+------+
| dan    | alarm  | 2014-05-14 12:00:00.000 |    1 |    1 |
| dan    | snooze | 2014-05-14 12:30:00.000 |    1 |    2 |
| dan    | snooze | 2014-05-14 12:50:00.000 |    2 |    3 |
| dan    | alarm  | 2014-05-14 13:00:00.000 |    2 |    4 |
| jim    | snooze | 2014-05-14 11:00:00.000 |    1 |    1 |
| jim    | snooze | 2014-05-14 12:45:00.000 |    2 |    2 |
| jim    | alarm  | 2014-05-14 13:45:00.000 |    1 |    3 |
+--------+--------+-------------------------+------+------+
于 2014-05-15T21:20:48.093 回答