从连接中删除字符

Remove characters from concatenation

我有一个 table 布局如下:

    CREATE TABLE dbo.tbl (
    Ten_Ref VARCHAR(20) NOT NULL,
    Benefit VARCHAR(20) NOT NULL
);

INSERT INTO dbo.tbl (Ten_Ref, Benefit)
VALUES ('1', 'HB'),
       ('1', 'WTC'),
       ('1', 'CB'),
       ('2', 'CB'),
       ('2', 'HB'),
       ('3', 'WTC');

然后我运行此代码执行转换和连接(我需要一个字段中的所有利益信息'

with [pivot] as

(
SELECT Ten_Ref
,[HB] = (Select Benefit FROM tbl WHERE t.Ten_Ref = Ten_Ref and Benefit = 'HB')
,[CB] = (Select Benefit FROM tbl WHERE t.Ten_Ref = Ten_Ref and Benefit = 'CB')
,[WTC] = (Select Benefit FROM tbl WHERE t.Ten_Ref = Ten_Ref and Benefit = 'WTC')
/*Plus 7 more of these*/

FROM tbl as t

GROUP BY Ten_Ref
)

select  p.ten_Ref
        /*A concatenation to put them all in one field, only problem is you end up with loads of spare commas*/
        ,[String] = isnull (p.HB,0) + ',' + isnull (p.cb,'') + ',' + isnull (p.wtc,'')

from [pivot] as p

我的问题是并非每个 ten_ref 都附带所有好处。

使用这段代码,在有空隙或 NULL 的地方,我最终会得到大量的双逗号,例如 'HB,,WTC'

我怎样才能让它只有一个逗号,而不管每个租户有多少福利?

您在找这样的东西吗?

SELECT  A.Ten_Ref,
        STUFF(CA.list,1,1,'') list
FROM tbl A
CROSS APPLY(
                SELECT ',' + Benefit
                FROM tbl B
                WHERE A.Ten_Ref = B.Ten_Ref
                ORDER BY Benefit
                FOR XML PATH('')
            ) CA(list)
GROUP BY A.ten_ref,CA.list

结果:

Ten_Ref              list
-------------------- ------------------
1                    CB,HB,WTC
2                    CB,HB
3                    WTC

或者如果你真的想使用 pivot 并手动连接,你可以这样做:

SELECT  Ten_Ref,
        --pvt.*,
        ISNULL(HB + ',','') + ISNULL(CB + ',','') + ISNULL(WTC + ',','') AS list
FROM tbl
PIVOT
(
    MAX(Benefit) FOR Benefit IN([HB],[CB],[WTC])
) pvt