Sql 当作为JSON返回时,如何从同一查询中获取ID列表

Sql 当作为JSON返回时,如何从同一查询中获取ID列表,sql,json,sql-server,Sql,Json,Sql Server,应用程序表格 app_id | app_name | app_status ------------------------------------- 1 scheduling INACTIVE 2 call ACTIVE 3 billing ACTIVE 4 order ACTIVE 我有一个疑问 从应用程序中选择*,其中app_status=“AC

应用程序
表格

app_id  |   app_name   |  app_status
-------------------------------------
  1         scheduling    INACTIVE
  2         call          ACTIVE
  3         billing       ACTIVE
  4         order         ACTIVE
我有一个疑问

从应用程序中选择*,其中app_status=“ACTIVE”表示JSON路径

此查询有一个
app\u id
字段。我还希望在
json
输出中附带一个字段
id
,其中包含所有
app\u id
,作为列表

因此,不是:

[{
    "app_id": 2,
    "app_name": "call",
    "status": "ACTIVE"
}, {
    "app_id": 3,
    "app_name": "billing",
    "status": "ACTIVE"
}, {
    "app_id": 4,
    "app_name": "order",
    "status": "ACTIVE"
}]
我会:

[{
    "apps": [{
        "app_id": 2,
        "app_name": "call",
        "status": "ACTIVE"
    }, {
        "app_id": 3,
        "app_name": "billing",
        "status": "ACTIVE"
    }, {
        "app_id": 4,
        "app_name": "order",
        "status": "ACTIVE"
    }],
    "ids": [2, 3, 4]
}]

这将返回正确的JSON

资料

质疑

输出

[
  {
    "apps": [
      {
        "app_id": 2,
        "app_name": "call",
        "app_status": "ACTIVE"
      },
      {
        "app_id": 3,
        "app_name": "billing",
        "app_status": "ACTIVE"
      },
      {
        "app_id": 4,
        "app_name": "order",
        "app_status": "ACTIVE"
      }
    ],
    "ids": [ 2, 3, 4 ]
  }
]

我无法理解为什么微软没有一个简单的解决方案,这似乎是一个共同的要求。一些版本的
JSON\u查询(STUFF(…FOR XML PATH(“”))
很流行,比如前面的这个。
with active_cte as (
    select * FROM tTable WHERE app_status = 'ACTIVE')
SELECT 
  (select * FROM active_cte FOR JSON PATH) apps,
  (select JSON_QUERY(concat('[',string_agg(app_id, ','),']'),'$') from active_cte) ids
for json path;
[
  {
    "apps": [
      {
        "app_id": 2,
        "app_name": "call",
        "app_status": "ACTIVE"
      },
      {
        "app_id": 3,
        "app_name": "billing",
        "app_status": "ACTIVE"
      },
      {
        "app_id": 4,
        "app_name": "order",
        "app_status": "ACTIVE"
      }
    ],
    "ids": [ 2, 3, 4 ]
  }
]