Sql多行合并为具有特定模式的单行

时间:2012-05-05 10:20:31

标签: sql-server sql-server-2008 sql-server-2005

Sql select query,它将多行合并为一行 使用sqlserver 2005及以上版本 我有两个表,即(tb_master,tb_tasks)

create table tb_tasks(
id int IDENTITY(1,1) NOT NULL,
id_tbmaster int NOT NULL,
Tasks nvarchar(max) NOT NULL
)

create table tb_master(
id int IDENTITY(1,1) NOT NULL,
grade nchar(10) NOT NULL,
name nvarchar(50) NOT NULL,
task_date datetime NOT NULL,
)

select * from tb_master
id grade name   task_date
1  A     John   2012-02-13 10:40:00.000
2  B     Tom    2012-02-13 10:40:00.000


select tb_tasks
id  id_tbmaster  Tasks
1     1          cooking food.
2     1          Programing 2 hours
3     1          Attending meeting 
4     2          Driving car
5     2          hangout with friends

尝试了此查询

select tasks + ' , ' as 'data()' from tb_tasks for xml path('')

提供输出

XML
cooking food ,  Programing 2 hours ,  Attending meeting ,  Driving car ,  hangout with friends , 

我需要输出

id Name  grade task_date                tasksDetails
1  John   A    2012-02-13 10:40:00.000  1)cooking food, 2)Programing 2 hours, 3)Attending meeting
2  Tom    B    2012-02-13 10:40:00.000  1) Driving car, 2)hangout with friends

我试过试试

select a.name,a.task_date,b.tasks =replace(select (CONVERT(VARCHAR,(ROW_NUMBER() OVER(ORDER BY id DESC)))) + ') ' + tasks + ' , ' as 'data()'
from tb_tasks for xml path(''))
from tb_master a inner join tb_tasks b
on a.id=b.id_tbmaster

提前致谢

1 个答案:

答案 0 :(得分:3)

此查询将为每个tb_master创建所请求的活动列表。两个指针:一个应匹配row_number()over()和查询中的排序以获得一致的结果,OUTER APPLY的最后一行中的数字3是分隔符中的字符数(在本例中为',')。如果您更改分隔符,则需要调整此数字。

select a.name,a.task_date, b.taskList
from tb_master a
OUTER APPLY
(
  select stuff ((select ' , '
                      + CONVERT(VARCHAR(10), ROW_NUMBER() 
                                                   OVER(ORDER BY id DESC))
                      + ') ' 
                      + tasks 
                   from tb_tasks b
                  where a.id = b.id_tbmaster
                  order by id desc
                for xml path (''))
               , 1, 3, '') taskList
) b

现场演示位于Sql Fiddle