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

兄弟们,这个SQL怎么写啊?
下面是Table内容
字段1     字段2     字段3
A1           2001     CSDN
A2           2002     IBM
A3           2000     IBM
A1           2002     CSDN
A3           2000     Oracle
A1           2002     Oracel


现在想根据字段1和字段2统计成下面的格式,如何写这个SQL啊
A1     2001     1     CSDN
A1     2002     2     CSDN/Oracle
A2     2002     1     IBM
A3     2000     2     IBM/ORACLE


------解决方案--------------------
create table tb(字段1 varchar(10),字段2 varchar(10),字段3 varchar(10))
insert into tb values( 'A1 ', '2001 ', 'CSDN ')
insert into tb values( 'A2 ', '2002 ', 'IBM ')
insert into tb values( 'A3 ', '2000 ', 'IBM ')
insert into tb values( 'A1 ', '2002 ', 'CSDN ')
insert into tb values( 'A3 ', '2000 ', 'Oracle ')
insert into tb values( 'A1 ', '2002 ', 'Oracel ')
go

--创建一个合并的函数
create function f_hb(@字段1 varchar(10),@字段2 varchar(10))
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ' '
select @str = @str + '/ ' + cast(字段3 as varchar) from tb where 字段1 = @字段1 and 字段2 = @字段2
set @str = right(@str , len(@str) - 1)
return(@str)
End
go

--调用自定义函数得到结果:

select m.字段1,m.字段2,m.cnt , n.字段3 from
(
select 字段1,字段2,count(*) cnt from tb group by 字段1,字段2
) m,
(
select distinct 字段1,字段2 ,dbo.f_hb(字段1,字段2) as 字段3 from tb
) n
where m.字段1 = n.字段1 and m.字段2 = n.字段2


drop table tb
drop function f_hb

/*
字段1 字段2 cnt 字段3
---------- ---------- ----------- ------------
A1 2001 1 CSDN
A1 2002 2 CSDN/Oracel
A2 2002 1 IBM
A3 2000 2 IBM/Oracle

(所影响的行数为 4 行)

*/
------解决方案--------------------
create function db0.fn_test(col1 varchar(10),col2 varchar(10), ifalg int)
returns varchar(100)
as
begin
declare @icount int --字段1 字段2
declare @str varchar(100)
set @str = ' '

select @str = @str + ', ' +字段3 from Table where 字段1=@col1 and 字段2 = col2
set @str = stuff(@str,1,1, ' ')

select @icount = count(1) from Table where 字段1=@col1 and 字段2 = col2
if (@iflag = 1)
set @str = cast(@icount as varchar(100))
return @str
end

go

select distinct 字段1,字段2,num = dbo.fn_test(字段1,字段2,1),字段3 = dbo.fn_test(字段1,字段2,0) from Table