### 案例陈述有问题

``````SELECT  CASE WHEN [Question Order] IN ( 6, 11 )
THEN CASE WHEN [Question Part Label] = 'Other (Please specify):'
ELSE [Question Part Label]
END
ELSE 'replace code here'
END,[Respondent ID]
FROM    Results
WHERE  [Question Order] IN ( 6, 11 ) AND [Answer Label] = 'Yes'
``````

`````` select
stuff((select ','+T2.[Question Part Label]   from Results as T2
where T1.[Respondent ID] = T2.[Respondent ID]    for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '')
as Label from Results as T1 group by T1.[Respondent ID]
``````

``````Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
``````

``````Respondent ID  [Question Order]  [Question Part Label]   [Answer Text]   [Answer Label]
124587          6                It was not clear          NULL           Yes
124587          6                Did not Undersstand       NULL           Yes
124589          6                Other (Please specify):   Not enough     Yes
125654          6                Too Fast                  NULL           Yes
124582          11               Not frequent              NULL           Yes
``````

``````Respondent ID           [Question Part Label]
124587                  It was not clear,Did not Undersstand
124589                  Not Enough
125654                  Too Fast
124582                  Not frequent
``````

#### 3 个答案:

``````DECLARE @Results TABLE
(
Respondent_ID INT,
[Question Order] INT,
[Question Part Label] VARCHAR(40),
);

INSERT @Results
SELECT       124587, 6, 'It was not clear',        NULL,         'Yes'
UNION SELECT 124587, 6, 'Did not Undersstand',     NULL,         'Yes'
UNION SELECT 124589, 6, 'Other (Please specify):', 'Not enough', 'Yes'
UNION SELECT 124654, 6, 'Too Fast',                NULL,         'Yes'
UNION SELECT 124582, 11, 'Not frequent',           NULL,         'Yes';

WITH x AS
(
SELECT Respondent_ID
FROM @Results
WHERE [Question Order] IN (6,11)
GROUP BY Respondent_ID
)
SELECT x.Respondent_ID, Label = STUFF((SELECT ',' + CASE
WHEN [Question Part Label] = 'Other (Please specify):' THEN [Answer text]
ELSE [Question Part Label] END
FROM @Results
WHERE [Question Order] IN (6,11)
AND Respondent_ID = x.Respondent_ID
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')
FROM x;
``````

`````` stuff((select ','+T2.[Question Part Label]
from Results as T2
where T1.[Respondent ID] = T2.[Respondent ID]
for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '')
``````

``````;WITH CTE AS
(
SELECT  T1.[Respondent ID],
stuff(( SELECT ','+T2.[Question Part Label]
FROM Results as T2
WHERE T1.[Respondent ID] = T2.[Respondent ID]
FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 1, '') as Label
FROM Results as T1
GROUP BY T1.[Respondent ID]
)

SELECT  CASE WHEN [Question Order] IN ( 6, 11 )
THEN CASE WHEN [Question Part Label] = 'Other (Please specify):'