+ -
当前位置:首页 → 问答吧 → SQL中的分组统计问题~~

SQL中的分组统计问题~~

时间:2011-11-05

来源:互联网

表中有两个字段name和type
现在要按照name来分组统计type的数量
SELECT name,COUNT(*)
FROM table
GROUP BY name;
这样写对不?

还是这样写:
SELECT name,COUNT(name)
FROM table
GROUP BY name;

作者: Amy_foreverlove   发布时间: 2011-11-05

同一个name的type有没有重复的?如果有重复的算1个,还是算多个?

作者: maco_wang   发布时间: 2011-11-05

这样就行:
SELECT name,COUNT(*)
FROM table
GROUP BY name;

作者: qianjin036a   发布时间: 2011-11-05

SQL code
SELECT name,COUNT(distinct type)
FROM table
GROUP BY name;

作者: ssp2009   发布时间: 2011-11-05

name没有null值时,结果相同

作者: roy_88   发布时间: 2011-11-05

SQL code

declare @t table (name varchar(1),type int,othercol int)
insert into @t
select 'a',1,1 union all
select 'a',1,2 union all
select 'a',2,1 union all
select 'b',1,1 union all
select 'b',1,2 union all
select 'b',3,1 union all
select 'c',1,1 union all
select 'c',2,null

select name,count(1) as [cou] from @t group by name
/*
name cou
---- -----------
a    3
b    3
c    2
*/
select name,count(distinct type) as [cou] from @t group by name
/*
name cou
---- -----------
a    2
b    2
c    2
*/

作者: maco_wang   发布时间: 2011-11-05

SQL code
declare @t table(name nvarchar(10))
insert @t select 'a'
insert @t select null

select name,COUNT(name),COUNT(*) from @t group by name

/*
name    (No column name)    (No column name)
NULL    0    1
a    1    1
*/

作者: roy_88   发布时间: 2011-11-05