If I understand you correctly, you have to list all values in the Correct
column for a specific question in the order of the AnswerId
in one concatenated string.
Here is a generic solution for a specific QuestionId
(Recursive CTE)
DECLARE @Answers TABLE (
[AnswerId] INT NOT NULL,
[QuestionId] INT NOT NULL,
[Correct] BIT NULL
);
INSERT INTO @Answers (AnswerId,QuestionId,Correct) VALUES
(22, 9, 0),
(23, 9, 0),
(24, 9, 1);
;WITH Partitioned AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionId ORDER BY AnswerId ASC) AS RowNumber
, COUNT(1) OVER (PARTITION BY QuestionId) AS ColumnCount
, CONVERT(VARCHAR(MAX), Correct) AS Correct
FROM
@Answers
WHERE
[QuestionId] = 9
),
Concatenated AS (
SELECT RowNumber, ColumnCount, Correct FROM Partitioned WHERE RowNumber = 1
UNION ALL
SELECT
P.RowNumber
, P.ColumnCount
, C.Correct + P.Correct AS Correct
FROM
Partitioned P
INNER JOIN Concatenated C
ON P.RowNumber = C.RowNumber + 1
)
SELECT
CONVERT(VARCHAR(20), Correct) AS Correct
FROM
Concatenated
WHERE
RowNumber = ColumnCount
Note: Change @Answers
to your table's name and remove the table declaration and inserts.
Another solution is to write a CLR function to concatenate the values in the Correct
column.