Skip to content
Advertisement

Get distinct column values to an array

Using below query I get the column values to an array. Now I want to get distinct column values from it.

DECLARE
@columns NVARCHAR(MAX) = '',

SELECT 
@columns+=QUOTENAME(Question_no) + ','
FROM
marks_details  order by Question_no

-- remove the last comma
SET @columns = LEFT(@columns, LEN(@columns) - 1);

marks_details

Submission_id   Question_no
    200             1
    200             2
    300             2
    301             3
    302             3

The @columns should be [1,2,3]

Advertisement

Answer

DECLARE @columns NVARCHAR(MAX) = '';

SELECT @columns += QUOTENAME(Question_no) + ','
FROM (
  SELECT Question_no
  FROM marks_details
  GROUP BY Question_no
) X
ORDER BY Question_no;

-- remove the last comma
SET @columns = LEFT(@columns, LEN(@columns) - 1);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement