sql - 从表中查询以获取 JSON 结果
问题描述
我有一张桌子
我想得到这样的 JSON 结果:
[
{
"Type":"I", //If group name is empty display ‘I’ otherwise, display ‘G’
"StartDate":"20/12/2020 8:00am", //This is the start time
"Additional":{ //Because it is non-group (GroupName is null), so Additional is an object
"Info":"having food"
}
},
{
"Type":"G", //Group by Date and Group Name.
"GroupName":"School", //If record has the same group name,
"StartDate":"20/12/2020 9:00am", //!!! Display the first entry’s start date
"Additional":[ // It is an array due to Group Name being a real value, the items in array is the record whose StartDate has the same Date value.
{
"StartDate":"20/12/2020 9:00am", //Display the start date
"Info":"Take bus"
},
{
"StartDate":"20/12/2020 9:30am",", //Display the start date
"Info":"On the beach"
}
]
},
{
"Type":"G",
"GroupName":"Class 1",
"StartDate":"20/12/2020 11:00am",
"Additional":[
{
"StartDate":"20/12/2020 11:00am",
"Info":"Restaurant "
},
{
"StartDate":"20/12/2020 13:00pm",
"Info":"Walk on Lane"
}
]
},
{
"Type":"I",
"StartDate":"20/12/2020 15:00pm",
"Additional":{
"Info":"In museum"
}
}
]
有人会帮助我吗?非常感谢。
我还附上了这张图片中的 JSON 数据,这样 JSON 格式会更清晰。
有错别字抱歉,这是新图:
解决方案
根据 Microsoft SQL Server 文档,FOR JSON
最适合您。它在 SQL Server 2016 及更高版本上受支持。
SELECT CASE
WHEN GroupName is null THEN 'I'
ELSE 'G'
END as Type
,GroupName
,StartDate .....
FROM table
FOR JSON AUTO;
推荐阅读
- angular - 如何避免输入类型号删除数字中的“0”结尾
- .htaccess - 如何通过 .htaccess 管理多端口?
- cassandra - 计数器更新如何在 cassandra 中工作?
- django - 保存到数据库后自动更新模型关系
- json - CloudFormation:模板的输出块中未解决的资源依赖关系 [Ec2Instance]
- python - 计算熊猫时间序列数据中最后3条记录的平均值
- angular - 将 ng-select 绑定到对象内部的对象
- spring-boot - 由于 Content-Type 标头,Multipart POST 在 Springboot 中不断失败
- javascript - 使用 gulp 进行版本控制
- java - 无法在 FTP 服务器上写入多个文件