1

我有以下格式的表格 -

orderNumber  |  orderName
-------------+------------
1            |  Pizza
1            |  Pasta

使用 SQL 查询,我期待以下格式的输出 -

{
    "data": [{
        "orderNumber":1,
        "orders": [
            {"orderName": "Pizza"},
            {"orderName": "Pasta"}
        ]
    }]
}

但我的实际输出格式如下 -

{
    "data": [
        {
            "orderNumber": 1,
            "orders" [
                {"orderName": "Pizza"}
            ]
        },
        {
            "orderNumber": 1,
            "orders": [
                {"orderName": "Pasta"}
            ]
        }
    ]
}

我正在使用的 SQL 查询是 -

SELECT
    (SELECT orderNumber as orderNumber,
        (SELECT orderName
         FROM sample_table b
         WHERE a.orderNumber = b.orderNumber
         FOR JSON PATH) AS orders
     FROM sample_table a FOR JSON PATH, ROOT('data')
    ) AS orderdata

谁能帮我吗?

4

2 回答 2

1

你想要一个分组查询

select 
   orderNumber,
   (select orderName 
    from sample_table b 
    where a.orderNumber = b.orderNumber 
    for json path) as orders 
from sample_table a 
group by orderNumber
for json path, root ('data') 

返回

{
    "data": [
        {
            "orderNumber": 1,
            "orders": [
                {
                    "orderName": "Pizza"
                },
                {
                    "orderName": "Pasta"
                }
            ]
        }
    ]
}
于 2021-10-18T13:59:06.850 回答
0
--You Can use distinct query to do so.

create table #temp
(orderNumber varchar(20),
orderName varchar(20))

insert into #temp 
values('1','Pizza'),
('1','Pasta'),
('2','KFC'),('2','MACD')

select distinct(orderNumber),
   (select orderName 
    from #temp b 
    where a.orderNumber = b.orderNumber 
    for json path) as orders 
from #temp a 
for json path, root ('data') 
于 2021-12-14T12:50:34.250 回答