日期:2014-05-18  浏览次数:20453 次

求帮一个简单的查询


id fee type
1 52 11
1 100 12
2 20 13
2 25 13
4 40 11

查询后实现
id fee type
1 152 mixed
2 45 13
4 40 11

算相同id的fee 总数,并且如果type数>=2的时候显示mixed,要求一条语句



------解决方案--------------------
SQL code
-->生成测试数据
 
declare @tb table([id] int,[fee] int,[type] int)
Insert @tb
select 1,52,11 union all
select 1,100,12 union 2,

------解决方案--------------------
SQL code



select id,sum(fee) as fee, 

case when (select count(1) from ta b where a.id=b.id group by b.type ) >=2

then 'mixed' else count(1) end  as type

from ta a

group by id

------解决方案--------------------
SQL code


create table ta ([id] int,[fee] int,[type] int)
Insert ta
select 1,52,11 union all
select 1,100,12 union all
select 2,20,13 union all
select 2,25,13 union all
select 4,40,11



select id,sum(fee) as fee,TYPE= case when count(1)>=2 then 'mixed' else LTRIM(max(type)) end
from 
(
select id,sum(fee) as fee,  type
from ta a
group by id,type
) aa
group by id


id          fee         TYPE         
----------- ----------- ------------ 
1           152         mixed
2           45          13
4           40          11