2012-05-05 44 views
2

SQL SELECT查詢這給使用sqlserver的2005和上述 合併多個行成一個單列 我有兩個表,即(tb_master,tb_tasks)的Sql多行合併成單個行與特定的圖案

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 

查詢我試圖提前

+0

+1對於DDL和數據。 –

+0

@BogdanSahlean:thnkx –

回答

3

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 

感謝這個查詢將創建的每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

+0

謝謝你,先生,請節省我的時間,好的解釋 –