Home > Back-end >  Sort an array of strings in SQL
Sort an array of strings in SQL

Time:01-26

I have a column of strings in SQL Server 2019 that I want to sort

Select * from ID 
[7235, 6784] 
[3235, 2334] 
[9245, 2784] 
[6235, 1284] 

Trying to get the result below:

[6784, 7235]
[2334, 3235]
[2784, 9245]
[1284, 6235]

CodePudding user response:

Given this sample data:

CREATE TABLE dbo.ID(ID int IDENTITY(1,1), SomeCol varchar(64));

INSERT dbo.ID(SomeCol) VALUES
('[7235, 6784]'),
('[3235, 2334]'), 
('[9245, 2784]'),
('[6235, 1284]');

You can run this query:

;WITH cte AS 
(
  SELECT ID, SomeCol, 
      i = TRY_CONVERT(int, value), 
      s = LTRIM(value)
    FROM dbo.ID CROSS APPLY 
    STRING_SPLIT(PARSENAME(SomeCol, 1), ',') AS s
)
SELECT ID, SomeCol, 
  Result = QUOTENAME(STRING_AGG(s, ', ') 
           WITHIN GROUP (ORDER BY i))
FROM cte
GROUP BY ID, SomeCol
ORDER BY ID;

Output:

ID SomeCol Result
1 [7235, 6784] [6784, 7235]
2 [3235, 2334] [2334, 3235]
3 [9245, 2784] [2784, 9245]
4 [6235, 1284] [1284, 6235]

CodePudding user response:

The source table has a column with a JSON array.

That's why it is a perfect case to handle it via SQL Server JSON API.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID int IDENTITY PRIMARY KEY, jArray NVARCHAR(100));
INSERT @tbl (jArray) VALUES
('[7235, 6784]'),
('[3235, 2334]'), 
('[9245, 2784]'),
('[6235, 1284]');
-- DDL and sample data population, end

SELECT t.*
    , Result = QUOTENAME(STRING_AGG(j.value, ', ') 
           WITHIN GROUP (ORDER BY j.value ASC))
FROM @tbl AS t
    CROSS APPLY OPENJSON(t.jArray) AS j
GROUP BY t.ID, t.jArray
ORDER BY t.ID;

Output

 ---- -------------- -------------- 
| ID |    jArray    |    Result    |
 ---- -------------- -------------- 
|  1 | [7235, 6784] | [6784, 7235] |
|  2 | [3235, 2334] | [2334, 3235] |
|  3 | [9245, 2784] | [2784, 9245] |
|  4 | [6235, 1284] | [1284, 6235] |
 ---- -------------- -------------- 
  •  Tags:  
  • Related