日期:2014-05-17  浏览次数:20497 次

求一条SQL汇总语句

--有如下三张表(t_people 人员表、t_room 房间表 、t_people_room 入住信息 )

--t_people 人员信息
p_id p_name 
70304           张三
70716           李四
80184           王五
80983           杨七
10026           钱八
11005 工一
12056 黄九
14052 叶儿
13087 李二

--t_room 房间信息
roomid roomname
1 201
2 202
3 203
4 205
5 206
6 214

--t_people_room 入住信息
id  p_id roomid
1 70716 1
2 70304 2
3 80184 2
4 80983 2
5 10026 6
6 11005   4
7 12056 4
8 14052 5

--现在统计要每个房间的入住人员信息,希望得如下统计结果
roomid roomname peoples
1 201 李四
2 202 张三、王五、杨七
3 203
4 205 工一、黄九
5 206 叶儿
6 214 钱八

--希望用一条语句得到每个房间入住过人员信息
--数据库为 Ms sqL 2005 

sql?统计

------解决方案--------------------

--> 测试数据: @t_people
declare @t_people table (p_id int,p_name varchar(4))
insert into @t_people
select 70304,'张三' union all
select 70716,'李四' union all
select 80184,'王五' union all
select 80983,'杨七' union all
select 10026,'钱八' union all
select 11005,'工一' union all
select 12056,'黄九' union all
select 14052,'叶儿' union all
select 13087,'李二'

--> 测试数据: @t_room
declare @t_room table (roomid int,roomname int)
insert into @t_room
select 1,201 union all
select 2,202 union all
select 3,203 union all
select 4,205 union all
select 5,206 union all
select 6,214

--> 测试数据: @t_people_room
declare @t_people_room table (id int,p_id int,roomid int)
insert into @t_people_room
select 1,70716,1 union all