0

I have a common table expression query like this.

;WITH Orders AS (
                    SELECT  OrderStatus,
                            OrderID,
                            OrderedBy,
                            OrderItems
                    FROM    Orders
                    WHERE   StudentGuid = @StudentGuid
                  )

The desired JSON array output should look like this.

[
 {
  "status":"Accepted",
  "orders":[
     {
        "OrderID":"100-1000",
        "OrderedBy":"John Smith"
     },
     {
        "OrderID":"100-1001",
        "OrderedBy":"John Smith"
     }
  ]
},
{
  "status":"Rejected",
  "orders":[
     {
        "OrderID":"100-1002",
        "OrderedBy":"John Smith"
     }
  ]
}
]

My current query is;

SELECT CAST((
                SELECT * 
                FROM (
                        SELECT (SELECT 'Accepted') AS [OrderStatus],
                               (SELECT CAST((
                                            SELECT OrderID,
                                                   OrderedBy,
                                            FROM    Orders
                                            WHERE   [OrderStatus] = 'Accepted'
                                            FOR JSON PATH
                                            ) AS NVARCHAR(MAX))) AS Orders
                        UNION       
                        SELECT (SELECT 'Rejected') AS [OrderStatus],
                               (SELECT CAST((
                                            SELECT OrderID,
                                                   OrderedBy,
                                            FROM    Orders
                                            WHERE   [OrderStatus] = 'Rejected'
                                            FOR JSON PATH
                                            ) AS NVARCHAR(MAX))) AS Orders
                ) AS Temp FOR JSON PATH ) AS NVARCHAR(MAX))

The problem with my query is it is not dynamic (as status are hard coded) and "orders node" in the final outcome fail to parse by JSON Formatters due to "unions."

How can I remove the hardcoding and make it dynamic with the CTE?

Thanks!

1 Answer 1

1

Looks like this can be done using subqueries.

    SELECT DISTINCT [status],
                    (SELECT orderID, 
                            orderedBy
                    FROM    Orders AS B
                    WHERE   [Status] = A.[Status]
                                FOR JSON PATH) AS Orders
    FROM Orders AS A
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.