求助!!!! SQL语句的写法!

zhupc 2005-06-07 07:04:56
有一表结构如下:
字段 UserId Age......
1 15
2 33
3 70
4 24
5 18
现在我需要分年龄统计人数,比如
0-----20 2
21----40 2
41以上 1
请问这个sql语句该如何写?
...全文
118 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
itmingong 2005-06-08
  • 打赏
  • 举报
回复
用CASE
yezhutou 2005-06-08
  • 打赏
  • 举报
回复
mark
zhupc 2005-06-08
  • 打赏
  • 举报
回复
thanks!
cliff1002 2005-06-07
  • 打赏
  • 举报
回复
用case语句吧

select count(*)
from (select userid,age,case when age<=20 then 1
when age>20 and age>=40 then 2
else 3
end case as agelevel
from table) a
group by a.agelevel
zhupc 2005-06-07
  • 打赏
  • 举报
回复
是这样的,一个是数据太多,一个是年龄段也多。如果像上面那样写,要遍历数据库很多次,即使有索引,存储过程也不得行,所以。。。。
wangrhliuyh 2005-06-07
  • 打赏
  • 举报
回复
不太清楚你的意思,如果效率太低可以加索引
如果要写的太多的话,可以考虑使用SP
如果是全部统计出来的话,在SP中使用临时表或cursor都可以的
zhupc 2005-06-07
  • 打赏
  • 举报
回复
这样写我也知道,但是数据量太大,这样做效率低,就是想要点好一点的办法
lovefootball 2005-06-07
  • 打赏
  • 举报
回复
上面是分条写的
如果你要一次取出来

select count(*) where age<=20 and age>=0 union select count(*) where age<=40 and age>=21 union select count(*) where age>=41

取到dataset是三条记录
hjf1223 2005-06-07
  • 打赏
  • 举报
回复
Select Count(*) From table Where age between 0 and 30
so on
lovefootball 2005-06-07
  • 打赏
  • 举报
回复
select count(*) from table where age<=.. and age>=..
lovefootball 2005-06-07
  • 打赏
  • 举报
回复
select count(*) where age<=.. and age>=..

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧