带有重置的SQL Server Row_Count

时间:2017-04-08 00:19:35

标签: sql sql-server tsql sql-server-2012 gaps-and-islands

我有6列:

Date, Account, Side, Symbol, Currency, Reset Flag (0 Yes, 1 No)

我希望对分区进行行计数,但只要Reset Flag列中出现0,就会重置行计数。前5列不是唯一的,但它们的组合形成了一组独特的列。

请帮助我!

我研究过的所有其他解决方案都因某些原因无效:/

1 个答案:

答案 0 :(得分:1)

这是一个空白和岛屿风格的问题。没有任何样本数据或期望的结果......

使用两个row_number()通过重置标记来识别组,并使用外部查询中的另一个来按ResetFlag和内部查询中创建的grp对行进行编号。

date, Account, Side, Symbol, Currency的顺序更改为您想要按行编号的那些列的顺序;为三个row_number()中的每一个保持相同的顺序。

/* ----- */ 
select 
    date
  , Account
  , Side
  , Symbol
  , Currency
  , ResetFlag
  , rn = case when ResetFlag = 0 then 0
         else row_number() over (
            partition by ResetFlag, grp
            order by date, Account, Side, Symbol, Currency)
         end
from (
  select *
    , grp = row_number() over (order by date, Account, Side, Symbol, Currency) 
          - row_number() over (
              partition by ResetFlag 
              order by date, Account, Side, Symbol, Currency)
  from t
  ) s
order by date, Account, Side, Symbol, Currency

rextester演示:http://rextester.com/VLCO32635

返回:

+------------+---------+------+--------+----------+-----------+----+
|    date    | Account | Side | Symbol | Currency | ResetFlag | rn |
+------------+---------+------+--------+----------+-----------+----+
| 2017-01-01 |       7 |    2 |      3 | 7,0000   |         1 |  1 |
| 2017-01-02 |       8 |    9 |      9 | 6,0000   |         1 |  2 |
| 2017-01-03 |       4 |    1 |      5 | 6,0000   |         1 |  3 |
| 2017-01-04 |       5 |    4 |      8 | 5,0000   |         0 |  0 |
| 2017-01-05 |       2 |    1 |      3 | 1,0000   |         1 |  1 |
| 2017-01-06 |       8 |    0 |      2 | 0,0000   |         0 |  0 |
| 2017-01-07 |       0 |    3 |      8 | 9,0000   |         1 |  1 |
| 2017-01-08 |       0 |    3 |      1 | 3,0000   |         1 |  2 |
+------------+---------+------+--------+----------+-----------+----+