运行 个 SQL 个服务器

Running count SQL server

有人可以帮我计算 SQL 服务器

中的行数吗
Id Date   Trend 
A 15-1-20 Uptrend
A 14-1-20 Uptrend
A 13-1-20 Uptrend
A 12-1-20 NULL
A 11-1-20 Uptrend
A 10-1-20 Uptrend
A 09-1-20 NULL

预期结果

Id Date   Trend    Counttrend
A 15-1-20 Uptrend      3
A 14-1-20 Uptrend      2
A 13-1-20 Uptrend      1
A 12-1-20 NULL        NULL
A 11-1-20 Uptrend      2
A 10-1-20 Uptrend      1
A 09-1-20 NULL        NULL


CREATE TABLE #TREND (ID Varchar(2),[DATE] Date ,TREND Varchar(10))

INSERT INTO #trend
  ( ID, [DATE], TREND )
VALUES
  ('A', '01-15-2020', 'Uptrend'), 
  ('A', '01-14-2020', 'Uptrend'), 
  ('A', '01-13-20', 'Uptrend'),
  ('A', '01-12-20', NULL),
  ('A', '01-11-20', NULL),
  ('A', '01-10-20', 'Uptrend'),
  ('A', '01-09-20', 'Uptrend');

试试这个:

SELECT src.Id, src.[Date], src.Trend, 
  CASE
    WHEN Trend IS NULL THEN NULL
    ELSE ROW_NUMBER() OVER (PARTITION BY Id, Trend, MasterSeq-SubSeq ORDER BY [Date])
  END AS TrendCnt
FROM (
  SELECT *,  
    ROW_NUMBER() OVER(PARTITION BY Id ORDER BY [Date]) As MasterSeq,
    ROW_NUMBER() OVER(PARTITION BY Id, Trend ORDER BY [Date]) +1 As SubSeq
    FROM aaa
) src
ORDER BY [Date] DESC;

你没有明确指定你想要的逻辑。您似乎想要自最近 NULL 日期以来的天数。您可以使用 window 函数轻松计算:

select t.*,
       (case when trend is not null
             then datediff(day,
                           max(case when trend is null then date end) over (order by date),
                           date)
        end)
from trend t
order by date desc;

Here 是一个 db<>fiddle 与您问题中的结果匹配。

并以稍微不同的方式实现相同的结果:

with cte as (
    select *
      -- Find the null transitions so we can row number them
      , sum(case when Trend is null then 1 else 0 end) over (order by [Date] asc) RowBreak
    from @Test
)
select *
  -- filter out the case when Trend is null
  , case when Trend is not null then row_number() over (partition by RowBreak, Trend order by [Date] asc) else null end
from cte
order by [Date] desc;