T-SQL:row_number partion没有重启计数

时间:2018-06-11 20:20:25

标签: sql-server tsql sql-order-by row-number

我正在使用以下代码来获取数据的排名。随附的结果是我得到的结果与我需要的结果。我不知道我做错了什么,但是非常感谢任何帮助。

SELECT 
    SHIPTO, NAV_PN, WQ_WORKED, CR_TS, ROW_COUNT,
    ROW_NUMBER() OVER (PARTITION BY WQ_WORKED ORDER BY CR_TS) AS ROW_COUNT
FROM 
    #TABLE

Code Results vs Needed results

1 个答案:

答案 0 :(得分:0)

根据您的图像,您希望按日期排序时计算连续的WQ_WORKED值。要做到这一点,首先需要建立分组(分区)标准,以便正确计算所需的值。

在这种情况下,您可以通过使用Tabibitosan(旅行者)方法来识别系列中的组,方法是首先为cr_ts排序的记录集中的每个记录创建一个row_number(如果是一个关联断路器,可能会通过另一个值创建一个row_number需要),然后从具有相同排序的row_number中减去,但是按要分组的值进行分区。

然后,可以将此中间组ID与原始分区值一起使用,以计算分析结果。在这种情况下,你的最终row_count。

使用提供的样本数据(基于附加图像和下面评论的扩展数据):

Drop Table #TABLE;
with DTA(SHIPTO, NAV_PN, WQ_WORKED, CR_TS) as (
  select 7703556, '1817953C1', 1, cast('6/1/2018' as date) union all
  select 7703556, '1817953C1', 1, cast('6/4/2018' as date) union all
  select 7703556, '1817953C1', 0, cast('6/5/2018' as date) union all
  select 7703556, '1817953C1', 0, cast('6/6/2018' as date) union all
  select 7703556, '1817953C1', 1, cast('6/7/2018' as date) union all
  select 7703556, '1817953C1', 0, cast('6/8/2018' as date) union all
  --Expanded dataset below here
  select 7703047, '1648518C1', 1, cast('6/12/2018' as date) union all --0 1 1
  select 7703047, '1648518C1', 1, cast('6/13/2018' as date) union all --2 4 2
  select 7703047, '2010358C1', 1, cast('6/12/2018' as date) union all --0 2 1
  select 7703047, '2010358C1', 1, cast('6/13/2018' as date) union all --2 3 2
  select 7813059, '1648518C1', 0, cast('6/12/2018' as date) union all --2 1 1
  select 7813059, '1648518C1', 1, cast('6/13/2018' as date) union all --2 2 1
  select 7813059, '2010358C1', 0, cast('6/12/2018' as date) union all --2 2 1
  select 7813059, '2010358C1', 1, cast('6/13/2018' as date)           --2 1 1
)
select SHIPTO, NAV_PN, WQ_WORKED, CR_TS
  into #TABLE
  from dta;

以下查询返回预期结果(对于原始数据):

with tabi as (
select dta.*
     , row_number() over (order by cr_ts)
     - row_number() over (partition by wq_worked order by cr_ts) grp
  from #TABLE dta
 where shipto = 7703556
)
select SHIPTO, NAV_PN, WQ_WORKED, CR_TS
     , row_number() over (partition by wq_worked, grp order by cr_ts) ROW_COUNT
  from tabi
 order by cr_ts

结果:

SHIPTO  NAV_PN      WQ_WORKED   CR_TS       ROW_COUNT
7703556 1817953C1   1           2018-06-01  1
7703556 1817953C1   1           2018-06-04  2
7703556 1817953C1   0           2018-06-05  1
7703556 1817953C1   0           2018-06-06  2
7703556 1817953C1   1           2018-06-07  1
7703556 1817953C1   0           2018-06-08  1

使用下面评论中提供的扩展数据集,您需要为各种分析函数添加其他分区条件:

with tabi as (
select dta.*
     , row_number() over (partition by SHIPTO, NAV_PN order by cr_ts)
     - row_number() over (partition by SHIPTO, NAV_PN, WQ_WORKED order by cr_ts) grp
  from #TABLE dta
)
select tabi.*
     , row_number() over (partition by SHIPTO, NAV_PN, WQ_WORKED, grp order by cr_ts) ROW_COUNT
  from tabi
 order by SHIPTO, NAV_PN, WQ_WORKED, cr_ts