我想在查询结果里面插入一列reqResult,这一列的值是根据另一列的值做的统计:
如果相同reqID对应的所有TestcaseResult为pass, reqResult=pass
如果相同reqID对应的任何一个TestcaseResult为fail, reqResult=fail
请问高手这个sql语句该咋写?
------解决方案--------------------
select a.*,case when b.TestcaseResult>1 then 'fail' else 'pass' end as TestcaseResult
from requirement a
left join (select reqID,SUM(case when TestcaseResult='fail' then 1 else 0 end) as TestcaseResult
from testcase group by reqID
)b
on a.reqID=b.reqID
------解决方案--------------------
if OBJECT_ID('tempdb..#temp', 'u') is not null drop table #temp;
go
create table #temp( reqID INT, TestcaseResult varchar(10));
insert #temp
select '1','pass' union all
select '1','pass' union all
select '1','pass' union ALL
select '2','pass' union ALL
select '2','fail'
--假如你的TestcaseResult只有两个值(pass,fail)的话
SELECT *,
reqResult = MIN(TestcaseResult) OVER(PARTITION BY reqID)
FROM #temp
--方法2
SELECT *,
reqResult = (CASE WHEN EXISTS(SELECT 1 FROM #TEMP B WHERE B.reqID=A.reqID AND TestcaseResult='fail') THEN 'fail' ELSE 'pass' END)
FROM #temp A
/*
reqID TestcaseResult reqResult
1 pass pass
1 pass pass
1 pass pass
2 pass fail
2 fail fail
*/