日期:2014-05-18  浏览次数:20539 次

简单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
希望大家给出最有效率的查询


------解决方案--------------------
--?
Select type,count(*) as cn from tb group by type
------解决方案--------------------
Select type,count(*) as count from tb group by type
------解决方案--------------------
select type , count(*) cnt from testdb group by type
------解决方案--------------------
Select type,Types=count(1) from tb
group by type
order by type

------解决方案--------------------
Select Type,[Count]=Count(*) From testdb Group By Type
------解决方案--------------------
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
------解决方案--------------------
select type, 条=count(*) from testdb group by type
------解决方案--------------------
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

*/

------解决方案--------------------
Select type,count(*)[count] from tb group by type
赚了。呵呵``

------解决方案--------------------
分析一下:你要得的结果是------统计出type类型相同的记录数所以设计到是TYPE字段

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


      很容易理解,你查询得到的结果是一张表,有type,和zhonglei 两个字段就很容易理解了