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

我希望在 SQL 中创建一个数据查询,以增量地对行组进行编号,在一个公共日期时间进行分组,并在下一个日期时间保持“组编号”增量,以此类推。这些“组号”不能为每个组重置,正如我在使用 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 列应该看起来像“必需的结果”列。

90172 次浏览

你不应该使用 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

我觉得你在找这个:

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

——这是我的回答,克里斯 · 巴兰斯先生:

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

——试试这个,它是为我工作..。