0

我有类似的 XML 数据

<Answers>
<AnswerSet>
    <Answer questionId="Name" IncludeInGroup="false">ds</Answer>
    <Answer questionId="Email" IncludeInGroup="false">sds</Answer>
    <Answer questionId="Password" IncludeInGroup="false">QqH4x4jhNCs=</Answer>
    <Answer questionId="GUID" IncludeInGroup="false">dsdsd</Answer>
    <Answer questionId="RegistrationIDInfo" IncludeInGroup="false">sdsd</Answer>
    <Answer questionId="Login" type="list" IncludeInGroup="false" value="1" color="blue">Enabled</Answer>
    <Answer questionId="FriendList" IncludeInGroup="false" RegionName="Friends" RepeatRegion="0">ds</Answer>   
    <Answer questionId="testDropdown" type="list" selectedValue="2" IncludeInGroup="false" TP="1" TP1="2">item2</Answer>
    <Answer questionId="testRadio" type="list" IncludeInGroup="false" value="3" color="222" test="123" a="1" a1="22">item234</Answer>
    <Answer questionId="TestCheckbox" type="list" value="Item1" RepeatRegion="0" IncludeInGroup="false">Item1</Answer>
    <Answer questionId="TestCheckbox" type="list" value="Item3" RepeatRegion="0" IncludeInGroup="false">Item3</Answer>
    <Answer questionId="TestCheckbox" type="list" value="Item1" RepeatRegion="1" IncludeInGroup="false">Item1</Answer>
    <Answer questionId="TestCheckbox" type="list" value="Item2" RepeatRegion="1" IncludeInGroup="false">Item2</Answer>
</AnswerSet>

需要通过repeatregion属性分组获取questionid="TestCheckbox"的数据

输出

项目 1,项目 3|项目 1,项目 2

我已尝试使用以下查询,但它返回 Item1|Item3|Item1|Item2

将 @Content 声明为 XML 设置 @Content='Above XML...' 将 @Field 声明为 varchar(100) 设置 @Field='TestCheckbox' SELECT ISNULL( STUFF( (select '|' + T.answers.value('. ', 'VARCHAR(max)') FROM @Content.nodes('Answers/AnswerSet/Answer[@questionId=sql:variable("@Field")]') AS T(answers) for xml path('')) , 1, 1, '') ,'')

请指导我获得以上输出。

谢谢。

4

1 回答 1

1

尝试这个

;with cte as
(
select 
t.Answers.value('@RepeatRegion', 'int') region,
T.answers.value('.', 'VARCHAR(max)') value
FROM @Content.nodes('Answers/AnswerSet/Answer[@questionId=sql:variable("@Field")]') AS T(answers) 
) 

select
    STUFF ((
        select '|' + v.results
        from
        (       
        SELECT distinct 
        top 100 percent
            region,
            stuff(
            (
                select cast(',' as varchar(max)) + c1.value
            from cte c1
            WHERE c1.region = cte.region
            for xml path('')
            ), 1, 1, '') AS results
        FROM
            cte
        order by cte.region

        ) v
        for xml path('')
    ),1,1,'')
于 2012-11-16T12:24:30.837 回答