如何解决运行计数 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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。