运行计数 SQL 服务器

问题描述

谁能帮我计算 sql Server 中的行数

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','01-13-20','01-12-20',NULL),'01-11-20','01-10-20','01-09-20','Uptrend');

解决方法

试试这个:

hi
,

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

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 是一个 dbfiddle,与您问题中的结果相匹配。

,

对于实现相同结果的稍微不同的方法:

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;