SQL Server Group Concat with Different characters

拥有回忆 提交于 2019-11-30 22:13:22

make a more human readable solution

Sorry, this is the best I can do with your requirement.

SQL Fiddle

MS SQL Server 2008 Schema Setup:

create table YourTable
(
  ParentID int,
  ChildName varchar(10)
);

insert into YourTable values
(1, 'Max'),
(1, 'Jessie'),
(2, 'Steven'),
(2, 'Lucy'),
(2, 'Jake'),
(3, 'Mark');

Query 1:

with T as 
(
  select ParentID,
         ChildName,
         row_number() over(partition by ParentID order by ChildName) as rn,
         count(*) over(partition by ParentID) as cc
  from YourTable
)
select T1.ParentID,
       (
         select case
                  when T2.rn = 1 and T2.cc > 1 then ' and '
                  else ', ' 
                end + T2.ChildName
         from T as T2
         where T1.ParentID = T2.ParentID
         order by T2.rn desc
         for xml path(''), type
       ).value('substring(text()[1], 3)', 'varchar(max)') as ChildNames
from T as T1
group by T1.ParentID

Results:

| PARENTID |            CHILDNAMES |
------------------------------------
|        1 |        Max and Jessie |
|        2 | Steven, Lucy and Jake |
|        3 |                  Mark |
select ParentID,STUFF((SELECT ' and '+ChildName
    FROM Table1 where ParentID=a.ParentID
     FOR XML PATH('')),1,4,'')  as cnmae from Table1 a
group by ParentID

SQL FIDDLE DEMO

Good logical question. Please check the query below (bit lengthy, but could not stop myself posting my small logic :)).

CREATE TABLE #SampleTable ([ParentID] int, [ChildName] varchar(6));

INSERT INTO #SampleTable VALUES (1, 'Max')
INSERT INTO #SampleTable VALUES (1, 'Jessie')
INSERT INTO #SampleTable VALUES (2, 'Steven')
INSERT INTO #SampleTable VALUES (2, 'Lucy')
INSERT INTO #SampleTable VALUES (2, 'Jake')
INSERT INTO #SampleTable VALUES (3, 'Mark')

select * From #SampleTable

;WITH T(xParentID, xChildName, xChildNameResult, xC1, xC2)AS
(
    SELECT * FROM(
    SELECT 
        ParentID ,
        ChildName, 
        CAST(ChildName AS NVARCHAR(MAX)) AS ChildNameResult,
        ROW_NUMBER() OVER (PARTITION BY [ParentID] ORDER BY ChildName) C1,
        COUNT(*) OVER (PARTITION BY [ParentID]) C2
    FROM #SampleTable)x WHERE x.C1=1

    UNION ALL

    SELECT ParentID, ChildName,
    CAST(T.xChildNameResult+(CASE WHEN C1=1 THEN '' WHEN C1=C2 THEN ' and ' ELSE ', ' END)+ChildName AS NVARCHAR(MAX)), C1, C2 
    FROM
    (
        SELECT 
        ParentID , 
            ChildName, 
            ROW_NUMBER() OVER (PARTITION BY ParentID order by ChildName) C1,
            COUNT(*) OVER (PARTITION BY ParentID) C2
        FROM #SampleTable
    )y INNER JOIN T ON y.ParentID=T.xParentID and y.c1=T.xC1+1
)SELECT xParentID, xChildNameResult FROM T where xC1=xC2
OPTION (MAXRECURSION 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!