请教计算一组资料出现次数。分不够将来再补上了,抱歉!
请教一下,若我要计算表A中两个字符之组合在表B中不同天出现的次数(条件:1.同一ID出现一次以上只计一次。 2.不同天出现才计算),要如何做比较好?
表A:
I1 I2
80 82
81 84
82 84
82 90
82 80
…
表B:
A1 06 6 2005 80
A1 06 6 2005 82
A1 09 23 2005 82
A1 09 23 2005 90
A1 06 7 2005 80
A1 06 13 2005 82
A1 06 13 2005 84
A2 01 17 2004 3
A2 01 17 2004 82
A2 01 17 2004 90
A2 01 17 2004 80
A2 12 7 2004 82
…
结果:
I1 I2 次数
80 82 2
81 84 0
82 84 1
82 90 1
82 80 1
…
------解决方案--------------------create table A(I1 varchar(10), I2 varchar(10))
insert into A values( '80 ', '82 ')
insert into A values( '81 ', '84 ')
insert into A values( '82 ', '84 ')
insert into A values( '82 ', '90 ')
insert into A values( '82 ', '80 ')
create table B(I1 varchar(30), I2 varchar(10))
insert into B values( 'A1 06 6 2005 ', '80 ')
insert into B values( 'A1 06 6 2005 ', '82 ')
insert into B values( 'A1 09 23 2005 ', '82 ')
insert into B values( 'A1 09 23 2005 ', '90 ')
insert into B values( 'A1 06 7 2005 ', '80 ')
insert into B values( 'A1 06 13 2005 ', '82 ')
insert into B values( 'A1 06 13 2005 ', '84 ')
insert into B values( 'A2 01 17 2004 ', '3 ')
insert into B values( 'A2 01 17 2004 ', '82 ')
insert into B values( 'A2 01 17 2004 ', '90 ')
insert into B values( 'A2 01 17 2004 ', '80 ')
insert into B values( 'A2 12 7 2004 ', '82 ')
go
if object_id( 'pubs..f_hb ') is not null
drop function f_hb
go
--创建一个合并的函数
create function f_hb(@I1 varchar(30))
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ' '
select @str = @str + ', ' + cast(I2 as varchar) from B where I1 = @I1
set @str = right(@str , len(@str) - 1)
return(@str)
End
go
--调用自定义函数得到结果:
select a.* , count(*) 次数 from A ,
(select distinct I1 ,dbo.f_hb(I1) as I2 from B) t
where charindex(a.I1 + ', ' + a.I2 , t.I2) > 0
group by a.I1,a.I2
drop t