您的位置:首页 > 数据库

[SQL]SQL类似统计功能的sql文

2014-03-24 20:24 113 查看
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

if object_id('test1') is not null
drop table test1
create table test1(
name varchar(20),
type int)
insert into test1
select 'a',0
union all select 'b',0
union all select 'fb',1
union all select 'fbf',2
union all select 'fdfs',1

select * from test1

create function ss()
returns varchar(1000)
as
begin
declare @sql varchar(1000)
set @sql=''
select @sql=@sql+','+ name from test1
set @sql=stuff(@sql,1,1,' ')
return @sql
end

select dbo.ss(),count_0=(select count(1) from test1 where type=0),
count_1=(select count(1) from test1 where type=1),
count_2=(select count(1) from test1 where type=2)
/*
我想要的结果是这样的
name         count_0   count_1   count_2
a,b,fb,fbf,fdfs       2       2         1

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: