| 发表于:2007-09-18 10:33:4711楼 得分:80 |
create table test(姓名 varchar(20),就餐日期 varchar(20),饭店名称 varchar(20),id int) insert into test select '张三 ', '2007-01-01 ', '百福楼 ',1 insert into test select '李四 ', '2007-01-01 ', '百福楼 ',2 insert into test select '张三 ', '2007-05-01 ', '梅园 ',3 insert into test select '刘德华 ', '2007-05-01 ', '梅园 ',4 insert into test select '刘德华 ', '2007-06-01 ', '幼儿园 ',5 insert into test select '张三 ', '2007-06-01 ', '幼儿园 ',6 insert into test select '周润发 ', '2007-06-01 ', '幼儿园 ',7 go create function f_str(@date varchar(20),@restaurant varchar(20)) returns varchar(200) as begin declare @ret varchar(200) set @ret= ' ' declare @t table(姓名 varchar(20),就餐日期 varchar(20),饭店名称 varchar(20)) insert into @t select distinct a.姓名,a.就餐日期,a.饭店名称 from test a,test b where a.姓名=b.姓名 and a.饭店名称 <> b.饭店名称 and a.就餐日期 <> b.就餐日期 and a.饭店名称=@restaurant and a.就餐日期=@date and exists(select 1 from test c where c.姓名 <> a.姓名 and c.饭店名称=a.饭店名称 and 就餐日期=a.就餐日期 and exists(select 1 from test where 姓名=c.姓名 and 饭店名称=b.饭店名称 and 就餐日期=b.就餐日期)) select @ret=@ret+ ', '+姓名 from @t set @ret=stuff(@ret,1,1, ' ') return @ret end go select a.就餐日期,a.饭店名称,dbo.f_str(a.就餐日期,a.饭店名称) as 姓名 from test a group by a.就餐日期,a.饭店名称 having charindex( ', ',dbo.f_str(a.就餐日期,a.饭店名称))> 0 --调用了两次函数,效率也不高 go /* 就餐日期 饭店名称 姓名 -------------------- -------------------- -------------------- 2007-05-01 梅园 刘德华,张三 2007-06-01 幼儿园 刘德华,张三 */ drop function f_str drop table test go | | |
|