帮忙写个sql!!!!
表信息如下
id socre type
----------------------------------
1 50 1
1 40 1
1 30 2
1 40 2
1 70 11
1 60 11
条件 : 如果表中存在tpye = 11 的则取 tpye = 11 的记录分数总和
如果表中不存在 tpye = 11 则取 type = 2 的记录分数总和
如果表中不存在 type = 2 则取 type = 1 的记录分数总和
[解决办法]
declare @t table (id int,socre int,type int)insert into @tselect 1,50,1 union allselect 1,40,1 union allselect 1,30,2 union allselect 1,40,2 union allselect 1,70,11 union allselect 1,60,11if(exists (select 1 from @t where type=11))select * from @t where type=11if(not exists (select 1 from @t where type=11))begin if(not exists (select 1 from @t where type=2)) select * from @t where type=1 else select * from @t where type=2end
[解决办法]
这样?
--> --> (Roy)生成測試數據 if not object_id('Tempdb..#T') is null drop table #TGoCreate table #T([id] int,[socre] int,[type] int)Insert #Tselect 1,50,1 union allselect 1,40,1 union allselect 1,30,2 union allselect 1,40,2 union allselect 1,70,11 union allselect 1,60,11Go--如果表中存在tpye = 11 的则取 tpye = 11 的记录分数总和-- 如果表中不存在 tpye = 11 则取 type = 2 的记录分数总和-- 如果表中不存在 type = 2 则取 type = 1 的记录分数总和 Select [type],[socre]=SUM([socre]) from #T where [type]=11 group by [type]union allSelect [type],[socre]=SUM([socre]) from #T where not exists(select 1 from #T where [type]=11) and [type]=2 group by [type]union allSelect [type],[socre]=SUM([socre]) from #T where not exists(select 1 from #T where [type] in(2,11)) and [type]=1 group by [type]
[解决办法]
--楼主是要分组合计,还是按条件合计的if object_id('tb') is not null drop table tbgocreate table tb( id int, socre int, type int)goinsert into tbselect 1,50,1 union allselect 1,40,1 union allselect 1,30,2 union allselect 1,40,2 union allselect 1,70,11 union allselect 1,60,11goif exists(select 1 from tb where type=11) select sum(socre) from tb where type=11else if exists(select 1 from tb where type=2) select sum(socre) from tb where type=2else if exists(select 1 from tb where type=1) select sum(socre) from tb where type=1go/*-----------130(1 行受影响)*/