Ask Your Question
2

How can I incorporate PIVOT into a SQL query that includes CROSS APPLY OPENJSON?

asked 2023-05-17 11:35:18 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-17 11:47:02 +0000

scrum gravatar image

Here is an example SQL query that demonstrates how to incorporate PIVOT into a query that includes CROSS APPLY OPENJSON:

SELECT *
FROM (
    SELECT 
        [key] AS 'Name', 
        value AS 'Value'
    FROM Table1
    CROSS APPLY OPENJSON(JSONColumn)
) AS t
PIVOT (
    MAX(Value) 
    FOR Name IN ([Name1], [Name2], [Name3])
) AS p

In this example, the query retrieves data from a table named Table1, which includes a JSON column named JSONColumn. The OPENJSON function is used to parse the JSON data and return a set of key/value pairs. The resulting dataset is then pivoted using the PIVOT function to transform the key/value pairs into columns. The PIVOT function aggregates the data using the MAX function.

The names of the columns in the resulting pivot table are specified in the IN clause of the PIVOT function. You can modify these column names to match your specific needs.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-17 11:35:18 +0000

Seen: 7 times

Last updated: May 17 '23