SQL Server 2008 将行连接到列

SQL Server 2008 concatenate rows to column

我正在使用 SQL Server 2008,我的数据集如下所示:

FormKey        Value      Category   
-------        -----      ------
123456         Gloves     PPE
123456         Hat        PPE
123456         Scalf      PPE
123456         Boots      PPE
987654         Glasses    PPE
987654         Harness    PPE
987654         Overalls   PPE

我正在尝试通过 FormKey 连接值和分组,这样我最终会得到:

Formkey       Value                        Category
-------       -----                        -------
123456        Gloves, Hat, Scalf, Boots     PPE
987654        Glasses, Harness, Overalls    PPE

但是,我得到了每个 Formkey 的所有值的连接。

我一直使用的代码是:

SELECT frd.formresultkey AS frk
    ,STUFF((
            SELECT ', ' + fra.value
            FROM [FormResultAnswers] FRA
            INNER JOIN [FormResultDetails] FRD ON FRA.[DetailKey] = FRD.[DetailKey]
            INNER JOIN [FormResults] FR ON FRD.[FormResultKey] = FR.[FormResultKey]
            WHERE FR.FormReference = 'PPE'
                AND frd.FormElementReference = 'PPE_List'
            FOR XML path('')
            ), 1, 1, '') AS Concatted
FROM [FormResultAnswers] FRA
INNER JOIN [FormResultDetails] FRD ON FRA.[DetailKey] = FRD.[DetailKey]
INNER JOIN [FormResults] FR ON FRD.[FormResultKey] = FR.[FormResultKey]

在此之后,我需要使用 Formkeys 匹配的连接值更新 table。有人可以帮忙吗?

您可以创建两个函数来连接值,如下所示:

IF EXISTS (SELECT  *
           FROM sys.objects
           WHERE object_id = OBJECT_ID(N'GroupValue')) 
DROP FUNCTION GroupValue;
GO
IF EXISTS (SELECT  *
           FROM sys.objects
           WHERE object_id = OBJECT_ID(N'GroupCategory')) 
DROP FUNCTION GroupCategory;
GO
CREATE FUNCTION dbo.GroupValue (@FormKey INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @VAL VARCHAR(MAX) = '';
    SELECT @VAL = @VAL + Value + ', '
    FROM (SELECT DISTINCT Value
          FROM YourTable
          WHERE FormKey = @FormKey) AS TT

    IF (LEN(@VAL) > 0)
        SET @VAL = LEFT(@VAL, LEN(@VAL) - 1)

    RETURN @VAL
END
GO
CREATE FUNCTION dbo.GroupCategory (@Formkey INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @VAL VARCHAR(MAX) = '';
    SELECT @VAL = @VAL + Category + ', '
    FROM (SELECT DISTINCT Category
          FROM YourTable
          WHERE FormKey = @FormKey) AS TT

    IF (LEN(@VAL) > 0)
        SET @VAL = LEFT(@VAL, LEN(@VAL) - 1)

    RETURN @VAL
END
GO

这是查询:

SELECT FormKey
      ,dbo.GroupValue(FormKey) AS Value
      ,dbo.GroupCategory(FormKey) AS Category
FROM YourTable
GROUP BY FormKey;

对您的查询进行一些修改将获取结果。试试这个。

SELECT FormKey,
       Stuff((SELECT ',' + Value
              FROM   Result b
              WHERE  a.FormKey = b.FormKey
                     AND a.Category = b.Category
              FOR xml path('')), 1, 1, '') value,
       Category
FROM   Result a
GROUP  BY FormKey,
          Category