日期:2014-05-19  浏览次数:20486 次

关于分类统计的问题,盼一语句.
字段一         字段二         字段三
1                       a                     001
2                       b                     002
1                       a                     003
1                       a                     001
1                       a                     003
2                       b                     005
2                       b                     003
...                  
像这样的数据(记录很大二十多万条),想统计出字段一,字段二相同,字段三中不同数据的个数(例如:字段一为1,字段二为a的不同记录为2)且能显示出这些记录(001,003)
谢谢!

------解决方案--------------------
create table test(字段一 int,字段二 varchar(10),字段三 varchar(10))
insert test select 1, 'a ', '001 '
union all select 2, 'b ', '002 '
union all select 1, 'a ', '003 '
union all select 1, 'a ', '001 '
union all select 1, 'a ', '003 '
union all select 2, 'b ', '005 '
union all select 2, 'b ', '003 '
go

create function dbo.fun(@a1 varchar(20),@a2 varchar(20))
returns varchar(100)
as
begin
declare @name varchar(8000)
set @name= ' '
select @name=@name+ ', '+字段三 from test where 字段一=@a1 and 字段二=@a2
group by 字段三
return stuff(@name,1,1, ' ')
end
go

select distinct 字段一,
字段二,
不同个数=(select count(distinct 字段三) from test where 字段一=a.字段一 and 字段二=a.字段二 ),
字段三=dbo.fun(字段一,字段二)
from test a

drop table test
drop function fun

1 a 2 001,003
2 b 3 002,003,005

------解决方案--------------------
create table t(col1 int,col2 varchar(10),col3 varchar(10))
insert t
select 1, 'a ', '001 ' union all
select 2, 'b ', '002 ' union all
select 1, 'a ', '003 ' union all
select 1, 'a ', '001 ' union all
select 1, 'a ', '003 ' union all
select 2, 'b ', '005 ' union all
select 2, 'b ', '003 '

create table t1 (col1 int,col2 varchar(10),col3 varchar(10))

insert t1
select Distinct col1,col2, col3 from t
go
create function fn(@col1 varchar(10),@col2 varchar(10))
returns varchar(100)
as
begin
declare @res varchar(100)
set @res = ' '
select @res = @res + ', '+col3 from t1 where col1 = @col1 and col2 = @col2
set @res = stuff(@res,1,1, ' ')
return @res
end

go
select col1,col2,icount = count(col3),co