日期:2014-05-17  浏览次数:20731 次

求一条统计的SQL语句或思路
参数标准表stad,数据表data
stad
类型 评价 符号 值
type_a 好 < 5
type_a 中 >= 5
type_a 中 < 10
type_a 差 >= 10
type_b 好 < 25
type_b 中 >= 25
type_b 中 < 40
type_b 差 >= 40
......

data
时间 参数a 参数b 参数c (备用) ...
2011-01-01 01:00:00 4 30 ...
2011-01-01 01:02:00 7 40 ...
2011-01-01 01:05:17 6 20 ...
......

type_a 表示参数a,type_b 表示参数b。现在想要求出对应评价的取值范围内的统计条数SQL语句该怎么写?

即最后结果大概表示为
 类型 评价 条数
a类型 好 123
a类型 中 55
a类型 差 16
b类型 好 456
b类型 中 77
b类型 差 22
......

不用存储过程拼语句只写一条SQL语句可以实现吗?

------解决方案--------------------
row_number() partition
可以解决的。
------解决方案--------------------
这两个表怎么没有关联的条件啊?

------解决方案--------------------
SQL code
with t as(
select 'type_a' 类型,
       case when 参数a < 5 then '好' 
               when 参数a >=5 and 参数a<10 then '中'
               else '差' end as 评价
from data
union all
select 'type_b' 类型, 
       case when 参数b < 25 then '好' 
               when 参数b >=25 and 参数b<40 then '中'
               else '差' end as 评价
from data
)
select 类型,评价,count(*) 条数
from t
group by 类型,评价

------解决方案--------------------
我想到最多的就是动态语句……如果是有后台程序处理的把stad表读进来,再拼接语句,不懂其他方法。