SQL Server : query columns to JSON object with group by

后端 未结 4 2041
有刺的猬
有刺的猬 2021-02-14 08:16

I have a table with 3 columns, I want to query that table such that the result will be a JSON object.

Sample data looks like this:

 CREATE TABLE #Test (         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-14 08:56

    This works (in SQL Server 2017, where STRING_AGG is available), but is quite clumsy. I'm not sure there's not a more elegant way.

    SELECT (
        SELECT 
           ID, 
           ValueV, 
           Keys = JSON_QUERY('["' + STRING_AGG(STRING_ESCAPE(Keys, 'json'), '","') + '"]')
        FOR JSON PATH
    )
    FROM #Test 
    GROUP BY ID, ValueV
    

    For SQL Server 2016 (which has no STRING_AGG, or STRING_ESCAPE for that matter):

    SELECT (
        SELECT ID, ValueV, Keys = JSON_QUERY(REPLACE(REPLACE(
            (
                SELECT Keys 
                FROM #Test t2 WHERE t2.ID = t1.ID AND t2.ValueV = t1.ValueV 
                FOR JSON PATH
            ),
            '{"Keys":', ''),
            '}', ''))
        FOR JSON PATH
    )
    FROM #Test t1
    GROUP BY ID, ValueV
    

    Even less elegant, but you take what you can get. At least we're not concatenating with FOR XML...

提交回复
热议问题