求帮一个简单的查询
表
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,要求一条语句
[解决办法]
-->生成测试数据 declare @tb table([id] int,[fee] int,[type] int)Insert @tbselect 1,52,11 union allselect 1,100,12 union 2,
[解决办法]
select id,sum(fee) as fee, case when (select count(1) from ta b where a.id=b.id group by b.type ) >=2then 'mixed' else count(1) end as typefrom ta agroup by id
[解决办法]
create table ta ([id] int,[fee] int,[type] int)Insert taselect 1,52,11 union allselect 1,100,12 union allselect 2,20,13 union allselect 2,25,13 union allselect 4,40,11select id,sum(fee) as fee,TYPE= case when count(1)>=2 then 'mixed' else LTRIM(max(type)) endfrom (select id,sum(fee) as fee, typefrom ta agroup by id,type) aagroup by idid fee TYPE ----------- ----------- ------------ 1 152 mixed2 45 134 40 11