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

功能统计!
表a:(用户使用功能模块记录表)
字段:user_id(用户ID) ,user_name(用户姓名), fun_id(功能模块代号),now_time(当前时间)
数据如:
00001,小明,1,2008-08-01
00001,小明,2,2008-08-02
00001,小明,3,2008-08-03
00002,小明,4,2008-08-04
00002,小明,1,2008-08-01
00003,小明,12,2008-08-02
00003,小明,6,2008-08-03
00003,小明,9,2008-08-04

表b:(功能模块说明表)
字段:fun_id(功能模块代号),fun_name(功能模块名称)
1,用户套餐功能1说明
2,用户套餐功能2说明
3,用户套餐功能3说明
4,用户套餐功能4说明
5,用户套餐功能5说明
6,用户套餐功能6说明
7,用户套餐功能7说明
8,用户套餐功能8说明
9,用户套餐功能9说明
10,用户套餐功能10说明
11,用户套餐功能11说明
12,用户套餐功能12说明

我想统计200808这个月各功能有多少人在用,SQL怎么写呢?
查询结果格式如:user_id ,user_name ,count (功能1),count (功能2),count (功能3),count (功能4),count (功能5)...count (功能12)


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

select user_id, user_name, 
  count(case when fun_id=1 then 1 end) f1,
  count(case when fun_id=2 then 1 end) f2,
  count(case when fun_id=3 then 1 end) f3,
...
  count(case when fun_id=12 then 1 end) f12
from a
group by user_id, user_name

------解决方案--------------------
如果是水晶报表的话可以用“交叉表专家”。
sql语句实现的话,先在开发环境中获得所有用户功能套餐,
再按照
select user_id, user_name, 
count(case when fun_id=1 then 1 end) f1,
count(case when fun_id=2 then 1 end) f2,
count(case when fun_id=3 then 1 end) f3,
...
count(case when fun_id=12 then 1 end) f12
from a
group by user_id, user_name
的格式在开发环境中把sql拼接好,最后执行。


------解决方案--------------------
1.如果表 b 就这12个功能模块 ,一直不会变化的话,你可以使用楼上的方法 ,使用 case 或者decode 来穷举
2.如果表 b 的功能模块会变化 ,那么一个sql应该是不能解决的吧 ,如果你是使用别的开发工具来做报表的话,pb中有crosstab 可以很方便的行转列 ;另外一种方式就是 使用存储过程 ,返回 结果集,或者动态建表,把结果集插进去吧