我有一张看起来像这样的表:
+--------+-------+-------+ |TestName|TestRun|OutCome| +--------+-------+-------+ | Test1 | 1 | Fail | +--------+-------+-------+ | Test1 | 2 | Fail | +--------+-------+-------+ | Test2 | 1 | Fail | +--------+-------+-------+ | Test2 | 2 | Pass | +--------+-------+-------+ | Test3 | 1 | Pass | +--------+-------+-------+ | Test3 | 2 | Fail | +--------+-------+-------+
该表用于存储测试结果的简短摘要。我想写一个查询(使用T-SQL,但任何方言都很好),它返回每个测试失败的构建数量。使用示例作为输入,它应返回如下结果集:
+--------+----------+ |TestName|Regression| +--------+----------+ | Test1 | 2 | +--------+----------+ | Test2 | 0 | +--------+----------+ | Test3 | 1 | +--------+----------+
请注意,查询应仅计算当前的“失败条纹”,而不是计算失败的总数。可以假设MAX(TestRun)是最近的运行。
有什么想法吗?
编辑:语法
答案 0 :(得分:3)
有点难看,但它有效。
create table dbo.tests
(
TestName nvarchar(10) not null
, TestRun int not null
, OutCome nvarchar(10) not null
)
insert into dbo.tests
select 'Test1', 1, 'Fail'
union all
select 'Test1', 3, 'Fail'
union all
select 'Test2', 1, 'Fail'
union all
select 'Test2', 3, 'Pass'
union all
select 'Test3', 1, 'Pass'
union all
select 'Test3', 3, 'Fail'
; with c (TestName, TestRun, OutCome, TestId)
as
(
select TestName, TestRun, OutCome
, dense_rank() over (order by TestRun) as TestId
from dbo.tests
)
select t.TestName, max(t.TestId) - mt.MaxPassedTestRun as FailedRuns
from c t
inner join
(
select TestName, sum(TestId) as MaxPassedTestRun
from
(
select TestName, TestId
from c
where OutCome = 'Pass'
union all
select TestName, 0 as TestRun
from c
where OutCome = 'Fail'
) mt
group by mt.TestName
) mt on t.TestName = mt.TestName
group by t.TestName, MaxPassedTestRun, mt.MaxPassedTestRun
答案 1 :(得分:1)
select a.TestName,a.TestRun,a.Outcome From table1 a join
Table1 b on a.TestName=b.testname
and a.Outcome='Fail'
and a.TestRun>b.TestRun
答案 2 :(得分:1)
以下是使用CTE的另一种方法:
;WITH streaks AS (
SELECT t.Name, t.Run, t.Outcome
FROM TestRuns t
INNER JOIN (SELECT Name, MAX(Run) AS MaxRun FROM TestRuns GROUP BY Name) maxes
ON maxes.Name = t.Name AND maxes.MaxRun = t.Run
UNION ALL
SELECT t.Name, t.Run, t.Outcome
FROM TestRuns t
INNER JOIN streaks s ON s.Name = t.Name AND s.Outcome = 0
WHERE t.Run = s.Run - 1 AND t.Outcome = 0
)
SELECT Name
, SUM(CASE WHEN Outcome = 0 THEN 1 ELSE 0 END) AS Regression
FROM streaks
GROUP BY Name
这里有SQL Fiddle个数据样本