Mohamad Shiralizadeh
Mohamad Shiralizadeh

Reputation: 8765

group by JSON Column that contains an array

I have the following table:

Table

that contains these data:

Data

How can I group by my array items in my JSON Column? and get this result:

Expected Result

Upvotes: 3

Views: 1120

Answers (2)

donPablo
donPablo

Reputation: 1959

If you cannot use OPENJSON, here is an alternative

Select
    aRole, COUNT(*) as cnt
From (

    Select
        a.ID
        ,b.Items as aRole
    From 
        (Select *
            ,replace(replace(replace(Roles,'[',''),']',''),'"','') as Rolesx
         From JSONgroup) a
    Cross Apply dbo.Split(a.Rolesx, ',') b
) c
 group by aRole

Upvotes: 1

D-Shih
D-Shih

Reputation: 46229

You can try to use OPENJSON with CROSS APPLY to make it.

SELECT
    col1,
     UserID
FROM T t1
CROSS APPLY
    OPENJSON(t1.Roles)
    WITH
        (
            col1 varchar(50) N'$'
        ) AS a

sqlfiddle

Upvotes: 1

Related Questions