将JSON查询结果嵌套在SQL Server 2016中

时间:2016-09-22 12:59:44

标签: sql-server json

我有以下测试数据:

create table #T (MeterID int,[Description] varchar(255),[Status] varchar(55),Date datetime2(0),Reading int)
insert into #T select 4201544,'Home test','Active','2016/03/23 06:13',105678
insert into #T select 4201544,'Home test','Active','2016/03/23 06:14',105682
insert into #T select 4201544,'Home test','Active','2016/03/23 06:15',105684
insert into #T select 4201544,'Home test','Active','2016/03/23 06:16',105685
insert into #T select 4201544,'Home test','Active','2016/03/23 06:17',105686
insert into #T select 4201544,'Home test','Active','2016/03/23 06:18',105688
insert into #T select 4201544,'Home test','Active','2016/03/23 06:19',105688
insert into #T select 4201544,'Home test','Active','2016/03/23 06:20',105689
insert into #T select 4201544,'Home test','Active','2016/03/23 06:21',105690

我将其提取到所需的JSON中,如下所示:

select
    [MeterID],
    [Description],
    [Status],
    (select
        [Date],
        [Reading]
    from
        #T
    for JSON path) [Readings]
from
    #T
group by
    MeterID,
    [Description],
    [Status]
for JSON path, ROOT ('Data')

在这种情况下,行数非常少,查询执行速度很快。但是,在生产中,这将应用于更多行。查询#T两次似乎效率低下。

有没有更好的方法来达到相同的效果?我尝试在#T。

的单个查询上应用别名失败

1 个答案:

答案 0 :(得分:1)

您无法避免两次扫描。也许这个查询会更好用:

with groups AS (
select
    [MeterID],
    [Description]
    from  #T) 
select groups.[MeterID], groups.[Description], [Status], [Date], [Reading]
    from groups join #T Readings on groups.MeterID = Readings.MeterID
for json AUTO, ROOT ('Data')

使用FOR JSON AUTO,您将获得嵌套结果(仍有两个连接),但您将避免昂贵的UDX和排序(我看到计划中排序运算符的成本约为60%,而表扫描的成本为20%)