在 SQL 服务器中用逗号分隔和填充额外空白的列分组

Grouping of columns with comma separated and padding extra blanks in SQL Server

我有一个 table 与下面类似的数据

Label   Value   ColorCode
--------------------------
M1      0.5     #C71585
M1      1.5     #808080
M2      1       #C71585
M2      2       #C71585
M2      1.6     #FFC0CB
M3      3       #9400D3

我希望数据转换如下:

Label   Data
-------------------------------------------
M1      0.5,"#C71585",1.5,"#808080","",""
M2      1,"#C71585",2,"#C71585",1.6,"#FFC0CB"
M3      3,"#9400D3","","","",""

解释:对于每个 Label ,我需要计算 table 中值的数量并选择最高的 count.In 这个例子,它是对于计数为 3 的 M2。

现在我必须附加基于标签的逗号分隔的值和颜色代码列。那部分我已经完成了。这里的问题是我需要能够附加计数较少的额外“”(双引号)。

例如,对于 M1 ,计数为 2(比最大计数少 1),因此我必须附加 1*2 "" 以匹配我的最大计数标签 (M2)。同样对于 M3,计数为 1(比最大计数小 2),因此我必须附加 2*2 ""(双引号)以与 M2 匹配。

这是我为获取逗号分隔数据而编写的查询。

SELECT
    T1.Label,
    STUFF((SELECT ', ' + CAST(T.Value AS VARCHAR) + ',"' + T.ColorCODE + '"'
           FROM Table1 T        
           WHERE T.Label = T.Label        
           ORDER BY T.Label
           FOR XML PATH('')), 1, 2, '') AS Data
FROM Table1 T1 
GROUP BY T1.Label
ORDER BY T1.Label

任何人都可以告诉我如何附加额外的双引号,如上所述。 非常感谢!

PS:我正在使用 SQL Server 2014 Express Edition

试试这个代码:

SELECT
    T1.Label
    , STUFF((
        SELECT ',' + CAST(T.Value AS VARCHAR) + ',"' + T.ColorCODE + '"'
        FROM @Table T       
        WHERE T.Label = T1.Label       
        ORDER BY T.Label
        FOR XML PATH('')
    ),1,1,'') AS Data
FROM @Table T1    
GROUP BY T1.Label
ORDER BY T1.Label

使用Replicate。我刚刚编辑了一些你的查询

SELECT
    T1.Label
    , STUFF((
        SELECT ',' + CAST(T.Value AS VARCHAR) + ',"' + T.ColorCODE + '"'
        FROM Table1 T       
        WHERE T.Label = T1.Label       
        ORDER BY T.Label
        FOR XML PATH('')
    ),1,1,'') + replicate(',"",""', max(count(*)) over () - count(*)) AS Data
FROM Table1 T1    
GROUP BY T1.Label

另一种解决方案!---

创建数据

CREATE TABLE TestC
(
     Label VARCHAR(10)
    ,Value   DECIMAL(10,2)
    ,ColorCode VARCHAR(20)
)
GO

INSERT INTO TestC VALUES
('M1',0.5,'#C71585'),
('M1',1.5,'#808080'),
('M2',1  ,'#C71585'),
('M2',2  ,'#C71585'),
('M2',1.6,'#FFC0CB'),
('M3',3  ,'#9400D3')
GO

解决方案

;WITH CTE1 AS
(
    SELECT  Label ,  MAX(COUNT(*)) OVER() - COUNT(*) c  FROM TestC
    GROUP BY Label
)
,CTE2 AS
(
    SELECT Label , CONCAT ( Value , ',"' , ColorCode , '"') Vals
    FROM TestC 
    UNION ALL
    SELECT c.Label , '""' Vals FROM CTE1 c
    INNER JOIN master..spt_values m  ON c.c >= m.number 
    WHERE m.type = 'p' AND c.c > 0
)
SELECT c.Label , 
        STUFF((
        SELECT ',' + Vals
        FROM CTE2 c1      
        WHERE c1.Label = c.Label       
        ORDER BY c1.Label
        FOR XML PATH('')
        ),1,1,'') cData
FROM CTE2 c 
GROUP BY c.Label

输出

Label      cData
---------- ---------------------------------------------------------
M1         0.50,"#C71585",1.50,"#808080","",""
M2         1.00,"#C71585",2.00,"#C71585",1.60,"#FFC0CB"
M3         3.00,"#9400D3","","",""

(3 rows affected)