如何在SQL中返回每个组的增量组编号

时间:2013-01-16 13:38:38

标签: sql sql-server tsql group-by

我想在SQL中创建一个数据查询,逐步对行组进行编号,按公共日期时间分组,并在下一个日期时间保持“组号”递增,依此类推。正如我在使用分区语句时看到的那样,这些“组号”不能为每个组重置。这是我的示例数据:

ts_DateTime          |ID   |Value|RowFilter|RequiredResult
--------------------------
2013/01/09 09:23:16  |8009 |0    |1        |1
2013/01/09 09:23:16  |8010 |0    |2        |1
2013/01/09 09:23:16  |8026 |0    |3        |1

2013/01/09 09:23:22  |8026 |0    |1        |2

2013/01/09 09:23:28  |8009 |0    |1        |3
2013/01/09 09:23:28  |8010 |0    |2        |3
2013/01/09 09:23:28  |8026 |0    |3        |3

2013/01/09 09:27:03  |8009 |0    |1        |4
2013/01/09 09:27:03  |8010 |0    |2        |4
2013/01/09 09:27:03  |8026 |0    |3        |4

2013/01/09 09:27:09  |8009 |0    |1        |5
2013/01/09 09:27:09  |8010 |0    |2        |5
2013/01/09 09:27:09  |8026 |0    |3        |5

2013/01/09 09:27:15  |8009 |0    |1        |6
2013/01/09 09:27:15  |8010 |0    |2        |6
2013/01/09 09:27:15  |8026 |0    |3        |6


我用来获取这些结果的查询是:

select hl.ts_DateTime,  hl.Tagname as [ID],  hl.TagValue as [Value],
ROW_NUMBER() OVER (PARTITION BY hl.ts_datetime ORDER BY hl.tagname) AS RowFilter
from Table1 hl

所以基本上,看一下RowFilter列,每个ts_DateTime分区得到一个唯一的ROW编号。我真正需要的是,对于每个ts_DateTime分区,RowFilter列应该看起来像Required result列。

3 个答案:

答案 0 :(得分:74)

您不应该使用ROW_NUMBER()

  • 使用DENSE_RANK()代替
  • 删除PARTITION BY

查询,

SELECT hl.ts_DateTime,  
       hl.Tagname as [ID],  
       hl.TagValue as [Value],
       DENSE_RANK() OVER (ORDER BY ts_datetime) AS RowFilter
FROM   Table1 hl 
ORDER  BY RowFilter

答案 1 :(得分:2)

我认为你正在寻找这个:

ROW_NUMBER() OVER (PARTITION BY hl.id ORDER BY hl.ts_DateTime) AS RowFilter

答案 2 :(得分:1)

--这是我的回答 Mr.Chris Ballance :

select 
   hl.ts_DateTime,  hl.Tagname as [ID],  hl.TagValue as [Value],
   ROW_NUMBER() OVER (PARTITION BY hl.ts_datetime ORDER BY hl.tagname) AS RowFilter,
   DENSE_RANK() OVER (PARTITION BY hl.ts_datetime ORDER BY hl.Tagname) AS RequiredResult
from Table1 h1

--试试这个它对我有用...