我有这种情况:
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和行= 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;
我希望我能说清楚我想要完成的事情。每一个建议都将受到高度赞赏。谢谢!
答案 0 :(得分:0)
试一试
示例强>
;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]
<强>返回强>
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))