Fetching values from a table without using CURSORS

你说的曾经没有我的故事 提交于 2019-12-07 14:31:37

问题


My table has the following structure

ID  MName  FName
1   Sunil Sachin
2   Sunil Sanjay
3   Sunil Wasim
4   Greg  Ricky
5   Ian   Mark

I want the query to return

1 Sunil Sachin, Sanjay, Wasim
2 Sunil Sachin, Sanjay, Wasim
3 Sunil Sachin, Sanjay, Wasim
4 Greg Ricky
5 Ian Mark

回答1:


You can use this method to do a 'group_concat' and get the results you want:

with Data(ID, MName, FName) as
(
    select 1, 'Sunil', 'Sachin'
    union
    select 2, 'Sunil', 'Sanjay'
    union
    select 3, 'Sunil', 'Wasim'
    union
    select 4, 'Greg', 'Ricky'
    union
    select 5, 'Ian', 'Mark'
)
select Data.ID, Data.MName, Names.FNames
from Data
    join 
    (
        select MName, left(names, len(names) - 1) as FNames
        from Data as extern
            cross apply (select FName + ', '
                         from Data as intern
                         where extern.MName = intern.MName
                         for xml path('')
                        ) pre_trimmed (names)
        group by MName, names
    ) Names ON Data.MName = Names.MName
order by Data.ID


来源:https://stackoverflow.com/questions/4153387/fetching-values-from-a-table-without-using-cursors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!