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

一个分类统计的问题,有点复杂
现有表   t_就餐记录
字段如下:
姓名           就餐日期                   饭店名称       id(自增列)
张三 2007-01-01 百福楼   1
李四 2007-01-01 百福楼   2
张三 2007-05-01 梅园   3
刘德华 2007-05-01 梅园   4
刘德华 2007-06-01 幼儿园   5
张三 2007-06-01 幼儿园   6
周润发 2007-06-01 幼儿园   7

想统计出来,在一起吃过两次饭以上的人员(两人,或两人以上)

统计出来的格式大概是这个样式
就餐日期         饭店名称         吃饭人员
2007-05-01     梅园                 刘德华,张三
2007-06-01     幼儿园             刘德华,张三

或者其他格式也可以,只要能看出是是一起吃过两次饭以上的人员就可以了

先谢谢了

------解决方案--------------------
create table t_就餐记录(姓名 varchar(20),就餐日期 datetime ,饭店名称 varchar(50) , id int)
insert t_就餐记录
select '张三 ', '2007-01-01 ', '百福楼 ', 1
union select '李四 ', '2007-01-01 ', '百福楼 ', 2
union select '张三 ', '2007-05-01 ', '梅园 ', 3
union select '刘德华 ', '2007-05-01 ', '梅园 ', 4
union select '刘德华 ', '2007-06-01 ', '幼儿园 ', 5
union select '张三 ', '2007-06-01 ', '幼儿园 ', 6
union select '周润发 ', '2007-06-01 ', '幼儿园 ', 7

go

---用函数
create function f(@dt datetime,@fn varchar(10))
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str= ' '
select @str=@str+ ', '+姓名 from t_就餐记录 where 就餐日期=@dt and 饭店名称=@fn
set @str=stuff(@str,1,1, ' ')
return @str
end

go


select 就餐日期,饭店名称,吃饭人员=dbo.f(就餐日期,饭店名称)
from t_就餐记录
group by 就餐日期,饭店名称


drop table t_就餐记录
drop function dbo.f

/* 结果


就餐日期 饭店名称 吃饭人员
------------------------------------------------------ -------------------------------------------------- ----------------------------------------------------------------------------------------------------------------
2007-01-01 00:00:00.000 百福楼 李四,张三
2007-05-01 00:00:00.000 梅园 刘德华,张三
2007-06-01 00:00:00.000 幼儿园 刘德华,张三,周润发

(3 row(s) affected)

*/
------解决方案--------------------
学习!
------解决方案--------------------
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