select sum(a.a) '0-10',sum(a.b) '10-20',sum(a.c) '20-30',sum(a.d) '30以上'from (select case when price>0 and price<=10 then 1 end as a,case when price>10 and price<=20 then 1 end as b,case when price>20 and price<=30 then 1 end as c,case when price>30 then 1 end as dfrom titles) as a
这是我用 CASE when 条件判断。老师说虽然说结果对,但是这个写着太复杂了,当遇到1000条。 是那我就要写几百 几千条CASE when 加以判断, 所以小弟在这求根据问题标题的要求写出结果一样的,比较简洁的语句,注意是聚合查询。
12 回答
蛊毒传说
TA贡献1895条经验 获得超3个赞
暂时还没有想到很好的解决方案. 我写的这个也不是太好,比较的复杂
select [a] as '0-10',[b] as '10-20',[c] as '20-30',[d] as '>30' from(
select 'a' as flag,sum(price) as sumprice from title where price>0 and price<=10
union all
select 'b' as b,sum(price) from title where price>10 and price<=20
union all
select 'c' as b,sum(price) from title where price>20 and price<=30
union all
select 'd' as b,sum(price) from title where price>30
) PRICE
pivot
(
sum(sumprice) for flag in ([a],[b],[c],[d])
)
as PVT
还需要在寻求比较优化的方法,谢谢!
- 12 回答
- 0 关注
- 574 浏览
添加回答
举报
0/150
提交
取消