选择JSON连接表

时间:2017-10-14 19:57:19

标签: sql sql-server json sql-server-2017

我想从2个表中选择一个json字符串的数据。第一个表应列出第二个表中的所有链接表,如

第一张表:

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

第二张表:

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

跟踪可以链接多个电台。

预期结果:

[{
        "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"
            }
        ]
    }
]

1 个答案:

答案 0 :(得分: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]