1

I am trying to write a query to get this result:

[{
    "server_name": "windows",
    "app_names": ["firebase", "news api", "video api"]
}, {
    "server_name": "linux",
    "app_names": ["game"]
}]

However this is the result I am getting:

[{
    "server_name": "windows",
    "app_names": ["firebase", "news api", "video api", "game"]
}, {
    "server_name": "linux",
    "app_names": ["firebase", "news api", "video api", "game"]
}]

Database tables:

A
server_id | server_name
-----------------------
1           windows
2           Linux


B
app_id | app_name
-----------------------
1        firebase
2        news api
3        video api
4        game


C
status_id | status  | server_id | app_id
----------------------------------------
1           UP          1           1
2           DOWN        1           2
3           DOWN        1           3
4           DOWN        2           4

Query that I have:

SET @output = (
    SELECT DISTINCT A.server_name,
        JSON_QUERY(REPLACE(REPLACE(( SELECT
            B.app_name
            FROM B
                INNER JOIN C ON
                    B.app_id = C.app_id
                INNER JOIN A ON
                    C.server_id = A.server_id
            FOR 
                JSON AUTO
            ), N'{"app_name":', N''),'"}', '"'
        )) AS [app_names]
    FROM
        A
    FOR JSON PATH
)

I am close to the result that I want, but don't know what I am missing out on. All the app_names appear no matter what I do.

1 Answer 1

1

Remove the A from the subquery so you have a correlated subquery:

SET @output = (
    SELECT DISTINCT A.server_name,
            JSON_QUERY(REPLACE(REPLACE(( SELECT B.app_name
                                         FROM B JOIN
                                              C
                                              ON B.app_id = C.app_id
                                         WHERE C.server_id = A.server_id
                                         FOR JSON AUTO
                                       ), N'{"app_name":', N''),'"}', '"'
                     )) AS [app_names]
    FROM A
    FOR JSON PATH
   )
Sign up to request clarification or add additional context in comments.

3 Comments

Why it did not work in the JOIN clause and succeeded in the WHERE?
@Jam1 . . . "work"? Well it does "work". It just doesn't do what you want. You can see the difference. With A in the subquery, it returns all the apps on every row.
Lol, you are right, what I meant as "work" was the intended result

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.