计算表中相同值的连续出现次数

问题描述 投票:0回答:1

使用SQL Server 2019标准版。我正在从卫星收集月球测量数据,并且需要检测测试在九个间隔(或系列)内“连续”失败的次数。数字一表示失败。 此表中有测试数据,我的预期输出查询如下。理解这里

连续

非常重要。如果测试在 5,7 和 9 上失败(报告 1),但在 6 和 8 上未失败,则不计入在内。因此,隐含地,1 不是有效结果。 DROP TABLE IF EXISTS #tmpTable CREATE TABLE #tmpTable ( mooniq int, testresult int, series bigint ) INSERT INTO #tmpTable (mooniq, testresult, series) VALUES (74904, NULL, 1), (74904, NULL, 2), (74904, NULL, 3), (74904, NULL, 4), (74904, 1, 5), (74904, 1, 6), (74904, 1, 7), (74904, NULL, 8), (74904, NULL, 9), (94904, NULL, 1), (94904, NULL, 2), (94904, NULL, 3), (94904, NULL, 4), (94904, 1, 5), (94904, 1, 6), (94904, 1, 7), (94904, 1, 8), (94904, 1, 9), (24904, NULL, 1), (24904, NULL, 2), (24904, NULL, 3), (24904, NULL, 4), (24904, 1, 5), (24904, NULL, 6), (24904, 1, 7), (24904, NULL, 8), (24904, 1, 9);

我正在尝试获取查询的输出以匹配此查询的输出:

--- The results should look like this query's results /* mooniq contiqs ------ ------- 24904 0 74904 3 94904 5 */ SELECT 'mooniq' = 74904, 'contiqs' = 3 UNION SELECT 'mooniq' = 94904 , 'contigs' = 5 UNION SELECT 'mooniq' = 24904 , 'contigs' = 0

到目前为止,我已经尝试过
here

列出的方法,但对于脾气暴躁的 Mooniq '24904' 并没有成功,因为虽然它有 3 次失败,但这些失败都不是连续的,因此不应被计算在内。 --An ambiguation of a business problem simplified for you --So far I've tried: with grouped_moons as ( select mooniq, testresult, dense_rank() over (order BY mooniq,series) drom , dense_rank() over (partition by testresult order by mooniq, series) DRPQ from #tmpTable t) select * from grouped_moons order by mooniq


sql sql-server window lag rank
1个回答
0
投票

小提琴:

https://dbfiddle.uk/8KvQo9Oq

(也有链接答案的正确方法) 理由是,由于您已经有了序列号,因此只需执行内联子查询即可获取最后一次传递案例的序列值。失败行的序列号和最后通过的序列号之间的差异就是您的失败连续次数。 Mooniq 的最大连续失败次数是您最长的连续失败次数。

对于单一失败返回 null 而不是 0,但您当然可以根据需要合并()或调整。

with cte as ( select *, case when t1.testresult = 1 then ( select max(t2.series) from #tmpTable t2 where t1.mooniq = t2.mooniq and t1.series > t2.series and t2.testresult is null ) end as last_fail_series_from_a_pass from #tmpTable t1 ) select mooniq, nullif(max(series - last_fail_series_from_a_pass),1) as continous_fail from cte where testresult = 1 group by mooniq

© www.soinside.com 2019 - 2024. All rights reserved.