69

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

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 列应该看起来像所需的结果列。

4

3 回答 3

120

你不应该使用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
于 2013-01-16T13:56:10.143 回答
10

我想你正在寻找这个:

ROW_NUMBER() OVER (PARTITION BY hl.id ORDER BY hl.ts_DateTime) AS RowFilter
于 2018-03-04T22:07:01.910 回答
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

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

于 2021-04-11T14:43:41.663 回答