2

I would like to select data from 2 tables into one json string. First table should list all linked tables from second table like

First table:

SELECT [orderNumber], [tcpState] 
FROM [Tracking]

Second table:

SELECT [startdate], [enddate], [tcpState], [orderNumber], [name]
FROM [Stations]

Tracking can link several stations.

Expected result:

[{
        "orderNumber": 123455,
        "tcpState": 3,
        "Stations": [{
                "startdate": "2011-05-06",
                "enddate": "2012-09-15",
                "tcpState": 3,
                "name": "Roger"
            },
            {
                "startdate": "2011-02-06",
                "enddate": "2012-05-15",
                "tcpState": 4,
                "name": "Hans"
            }
        ]
    },
    {
        "orderNumber": 1566,
        "tcpState": 3,
        "Stations": [{
                "startdate": "2011-06-06",
                "enddate": "2012-08-15",
                "tcpState": "6",
                "name": "Mike"
            },
            {
                "startdate": "2011-03-06",
                "enddate": "2012-03-15",
                "tcpState": "6",
                "name": "Tom"
            }
        ]
    }
]
4

1 回答 1

0

好的,首先你强迫我在我的 linux 上安装 sql-server 2017 只是为了测试查询,因为没有可用的在线测试器,所以我有点讨厌你,但是谢谢,Docker 在那里......


有两种方法可以做到:

容易的,你在困难的之后找到了

使用FOR JSON AUTO

SELECT 
    [Tracking].[orderNumber], 
    [Tracking].[tcpState],  
    [Stations].[startdate],
    [Stations].[enddate],
    [Stations].[tcpState],
    [Stations].[name]
FROM [Tracking]
LEFT JOIN [Stations] 
    ON [Tracking].[orderNumber] = [Stations].[orderNumber]
FOR JSON AUTO

最难的,自己制作 JSON

/!\ 这使用STRING_AGG函数,SQL-server 2017 及之后仅 /!\

SELECT 
    '['+iif(STRING_AGG(t1.[orderNumber],',') IS NOT NULL, 
        STRING_AGG(
        '{'+
        '"orderNumber":'+CONVERT(varchar(10), t1.[orderNumber])+','+
        '"tcpState":'+CONVERT(varchar(10), t1.[tcpState])+','+
        '"Stations":'+t1.Stations+
        '}'
        , ','), '')+
    ']' json
FROM
(
    SELECT 
    t.[orderNumber], 
    t.[tcpState],  
    '['+ iif(STRING_AGG(s.[orderNumber],',') IS NOT NULL, 
        STRING_AGG(
        '{'+
        '"startdate":"'+s.[startdate]+'",'+
        '"enddate":"'+s.[enddate]+'",'+
        '"tcpState":'+CONVERT(varchar(10), s.[tcpState])+','+
        '"name":"'+s.[name]+'"'+
        '}'
        , ','), '')+']' Stations
    FROM [Tracking] t
    LEFT JOIN [Stations] s ON t.[orderNumber] = s.[orderNumber]
    GROUP BY t.[orderNumber], t.[tcpState]
) t1
GROUP BY t1.[orderNumber]
于 2017-10-15T23:21:22.810 回答