开发者

Fetching values from a table without using CURSORS

开发者 https://www.devze.com 2023-01-24 07:24 出处:网络
My table has the following structure IDMNameFName 1Sunil Sachin 2Sunil Sanjay 3Sunil Wasim 4GregRicky 5Ia开发者_Go百科nMark

My table has the following structure

ID  MName  FName
1   Sunil Sachin
2   Sunil Sanjay
3   Sunil Wasim
4   Greg  Ricky
5   Ia开发者_Go百科n   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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消