sql新手问基本的sql语句的问题
本帖最后由 pretystar 于 2013-08-22 10:22:56 编辑 我想在查询结果里面插入一列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
/*
reqIDTestcaseResultreqResult
1passpass
1passpass
1passpass
2passfail
2failfail
*/