分段统计的查询
表1:
user name price
1 q 2
2 w 6
2 e 7
3 r 4
3 y 5
4 u 5
怎么查询表1中同一user 的price总和在同一范围如(2~5,6~8,>8等)内的数目
例如user=2 的sum(price)=6+7=13 ,user=3 的sum(price)=4+5=9 都在 >8的范围内,user数目为2个。
请大哥们帮忙,这个判断查询SQL怎么写?(oracel)
------解决方案--------------------select user_id,count(*)
from table1
where user_id in (select user_id
from table1
group by user_id
having sum(price) >=9)
group by user_id;
------解决方案--------------------假如3种情况都要的话,可以用decode函数来实现。
对
select user_id from table1 group by user_id
之后的结果集作处理。
------解决方案--------------------不知道LZ是不是这个意思 ...
======================sql==========================
SQL code
select decode(yy.grade,'A','2~5','B','6~8','C','large 8') as gradeClass,
count(yy.grade) as gradeCount
from (
select zz.userid,
case when (zz.price)>=2 and (zz.price)<=5
then 'A'
when (zz.price)>=6 and (zz.price)<=8
then 'B'
when zz.price > 8
then 'C'
end as grade
from (
select tt.userid,
sum(tt.price) as price
from tablename tt
group by tt.userid
)zz
)yy
group by yy.grade;