简体   繁体   中英

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]

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);

I would recommend:

select @columns = string_agg( question_no, ',') within group (order by question_no)
from (select distinct question_no
      from marks_details
     ) md;

Here is a db<>fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM