使用 SQL 中其他列的混合值创建 varchar 列

Create varchar column with mixed values from other columns in SQL

我有这个场景:

CREATE TABLE tbl(templateId INT, id INT, name NVARCHAR(50), value NVARCHAR(50), row INT);

INSERT INTO tbl(templateId, id, name, value, row) 
VALUES
(1, 12, 'question1', '5 To 10', 1),
(2, 12, 'question2', 'washing machine', 1),
(3, 12, 'question3', 'yes', 1),
(4, 12, 'question2', 'tv', 2),
(5, 12, 'question1', '11 To 15', 2),
(6, 12, 'question1', '16 To 20', 2),
(7, 12, 'question4', 'employed' 2);

数据必须按id和行分组 我需要的是另一列包含如下数据的列:

-如果我们在同一行上有不同的问题(按 id = 12 和 row = 1 分组):

(question1: (5 To 10) [AND] question2: (washing machine) [AND] question3: (yes))

-如果我们在同一行有不同的问题,其中一个有很多答案,它应该看起来像这样(id = 12 和 row = 2):

(question2: (tv) [AND] question1: (11 To 15, 16 To 20) [AND] question4: (employed))

我成功创建了第一个案例,但我在创建第二个案例时遇到了问题。第二次我创建了类似

的东西
(question2: (tv) [AND] question1: (11 To 15) OR question1:(16 To 20) OR question4:(employed)) 

但这不好,问题1的答案必须用逗号分隔,而且名字不应该每次都显示。而且,它只在前两个名字之间放置[AND],它应该在question1 [AND] question4 之间,我只是不知道如何替换那个OR...

我创建了一个这样的函数:

declare @result varchar(1000), @name1 varchar(250), @name2 varchar(250), 
@duplicates int;
set @result = '';
set @duplicates = 0;
set @name1 = '';
set @name2 = '';

SELECT @result = @result + ' [AND] ' +  t.name + ': (' + t.value + ')',
@duplicates = (len(@result) - len(replace(@result,t.name,''))) / 
LEN(t.name)
FROM tbl t
WHERE t.id = @table_id and t.row = @row

if(len(@result)>0)
  if (@duplicates > 1) 
    begin
         SET @result =replace(substring(@result, 7, LEN(@result) - 4), ' 
 [AND] ', ' OR ');
         SET @name1 = LEFT(@result,CHARINDEX(': ',@result)-1);
         SET @name2 = SUBSTRING(SUBSTRING(@result,CHARINDEX('OR ', @result) 
 + 2,LEN(@result)), 0,CHARINDEX(':', @result) + 0)

         if (@name1 <> @name2)
         begin
            SET @result=STUFF(@result, CHARINDEX('OR', @result), LEN('OR'), 
 '[AND]')
         end 
    end 
else
    begin
         SET @result=substring(@result, 7, LEN(@result) - 4);  
    end

return @result;  

我希望我能弄清楚我想要完成的事情。每一个建议将不胜感激。谢谢!

试一试

例子

;with cte as (
Select top 1 with ties
       [id]
      ,[row]
      ,[name]
      ,TempValue =  Stuff((Select ', ' + value From tbl Where [Row]=A.[Row] and [Name]=A.[Name] For XML Path ('')),1,2,'')
      ,RN        =  Row_Number() over (Partition By [id],[row] Order by templateId)
 From tbl A
 Order by Row_Number() over (Partition By ID,[name],row order by templateid)
)
Select [Row]
      ,NewValue = '('+Stuff((Select ' [AND] ' +concat(Name,': (',TempValue,')') From cte Where [Row]=A.[Row] Order by RN For XML Path ('')),1,7,'')+')'
 From cte A
 Group By [Row]

Returns

Row NewValue
1   (question1: (5 To 10) [AND] question2: (washing machine) [AND] question3: (yes))
2   (question2: (tv) [AND] question1: (11 To 15, 16 To 20) [AND] question4: (employed))