简单sql分组统计问题

一个表如下:testdb
name type
a 0
b 0
fd 1
fdf 2
kvlc 1

如何用sql语句统计出type类型相同的记录数,最好在一个sql语句中完成。
多次查询的我也知道。
例如可以统计出: 0值的2条 1值的2条 2值的1条,
type类型个数已经知道为0-5
希望大家给出最有效率的查询
...全文
245 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
woaiguainv 2007-08-30
  • 打赏
  • 举报
回复
分析一下:你要得的结果是------统计出type类型相同的记录数所以设计到是TYPE字段

分类查询可以得到: select type,count(*) as zhonglei from testdb grouop by type


      很容易理解,你查询得到的结果是一张表,有type,和zhonglei 两个字段就很容易理解了
wuxinyuzhu 2007-08-30
  • 打赏
  • 举报
回复
是的 是我自己想的 顺便帮我优化一下
请大家指教一下
welove1983 2007-08-30
  • 打赏
  • 举报
回复
wuxinyuzhu() ... ~~~
这个LZ没要求这么做吧? 汗
wuxinyuzhu 2007-08-30
  • 打赏
  • 举报
回复
刚才的错了
改一下
declare @t table(name varchar(20),type int)
insert into @t
select 'a',0
union all select 'b',0
union all select 'fb',1
union all select 'fbf',2
union all select 'fdfs',1


declare @b varchar(1000)
set @b=''
select @b=case @b when ''then '' else @b+',' end +rtrim(name) from @t

select @b name,count_0=sum(case type when 0 then 1 end),
count_1=sum(case type when 1 then 1 end),
count_2=sum(case type when 2 then 1 end)
from @t
pt1314917 2007-08-30
  • 打赏
  • 举报
回复
Select type,count(*)[count] from tb group by type
赚了。呵呵``
wuxinyuzhu 2007-08-30
  • 打赏
  • 举报
回复
declare @t table(name varchar(20),type int)
insert into @t
select 'a',0
union all select 'b',0
union all select 'fb',1
union all select 'fbf',2
union all select 'fdfs',1


declare @b varchar(1000)
set @b=''
select @b=case @b when ''then '' else @b+',' end +rtrim(name) from @t group by name

select @b name,count_0=sum(case type when 0 then 1 end),
count_1=sum(case type when 1 then 1 end),
count_2=sum(case type when 2 then 1 end)
from @t

/*
是不是要的结果是这样的
name count_0 count_1 count_2
a,b,fb,fbf,fdfs 2 2 1

*/
Limpire 2007-08-30
  • 打赏
  • 举报
回复
select type, 条=count(*) from testdb group by type
tbxl 2007-08-30
  • 打赏
  • 举报
回复
declare @t table (name varchar(20),type int)
insert into @t
select 'a', 0
union select 'b', 0
union select 'fd ', 1
union select 'fdf ', 2
union select 'kvlc ', 1

select type ,cn =count(1)
from @t
group by type
welove1983 2007-08-30
  • 打赏
  • 举报
回复
50分那...汗
love16 2007-08-30
  • 打赏
  • 举报
回复
呵呵,这个问题真的有点容易!
dobear_0922 2007-08-30
  • 打赏
  • 举报
回复
大哥们,count(1)比count(*)效率高
SoftwKLC 2007-08-30
  • 打赏
  • 举报
回复
Select Type,[Count]=Count(*) From testdb Group By Type
dawugui 2007-08-30
  • 打赏
  • 举报
回复
直接group by 就行了.这分送得有点亏.
dobear_0922 2007-08-30
  • 打赏
  • 举报
回复
Select type,Types=count(1) from tb
group by type
order by type
dawugui 2007-08-30
  • 打赏
  • 举报
回复
select type , count(*) cnt from testdb group by type
fa_ge 2007-08-30
  • 打赏
  • 举报
回复
Select type,count(*) as count from tb group by type
WangZWang 2007-08-30
  • 打赏
  • 举报
回复
--?
Select type,count(*) as cn from tb group by type

34,873

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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