Home > Back-end >  How to perform a two column split by linking your data in sql server
How to perform a two column split by linking your data in sql server

Time:09-02

My db is on SQL server

I have a situation where I have a column that brings me the phase of my card and a column that brings me the date that this card entered the phase, but they are in the format of an "Array". How can I link the phase name with its entry date via query?

card_id phase_history firstTimeIn
8837 [Start, Compliance, Contact, Down] [2022-08-11T13:44:24 00:00, 2022-08-11T13:44:25 00:00, 2022-08-25T17:37:19 00:00, 2022-08-11T13:44:26 00:00]
6596 [Start, Compliance, Contact, Down] [2022-03-11T13:44:24 00:00, 2022-04-11T13:44:25 00:00, 2022-04-25T17:37:19 00:00, 2022-04-11T13:44:26 00:00]
2416 [Start, Contact, Up] [2022-08-02T02:22:31 00:00, 2022-08-02T02:22:31 00:00, 2022-08-02T12:13:32 00:00]
5424 [Start, Compliance, Contact, Lead, Down] [2022-09-01T12:51:24 00:00, 2022-09-01T12:51:25 00:00, 2022-09-01T13:25:52 00:00, 2022-09-01T12:51:26 00:00, 2022-09-01T16:47:31 00:00]

I would like it to be like this:

card_id phase_history firstTimeIn
8837 Start 2022-08-11T13:44:24 00:00
8837 Compliance 2022-08-11T13:44:25 00:00

If anyone has any other suggestions on how to handle this I would appreciate it.

CodePudding user response:

You can use OPENJSON to convert the array rows into new rows by the card_id column, and use TRIM to remove any extraneous brackets and whitespaces.

SELECT d.card_id, a.phase_history, a.firstTimeIn
FROM cards d
CROSS APPLY (
   SELECT 
   TRIM('[ ]' FROM c.[value]) AS phase_history, 
   TRIM('[ ]' FROM s.[value]) AS firstTimeIn
   FROM OPENJSON(CONCAT('["', REPLACE(d.phase_history, ',', '","'), '"]')) c
   LEFT OUTER JOIN OPENJSON(CONCAT('["', REPLACE(d.firstTimeIn, ',', '","'), '"]')) s 
      ON c.[key] = s.[key]
) a 
WHERE a.phase_history IN ('Start', 'Compliance')
AND card_id = 8837

Result Set:

card_id phase_history firstTimeIn
8837 Start 2022-08-11T13:44:24 00:00
8837 Compliance 2022-08-11T13:44:25 00:00

The real solution, however, would be to adjust your database design. Storing multiple values in an array format will cause you a lot of problems in the future. Fixing it now rather than later will prevent future headaches.

See Fiddle.

  • Related