【发布时间】:2021-08-24 06:57:55
【问题描述】:
我有一个这样的表结构:
我想以这种形式从这个表中创建一个 JSON:
{
"EntityId": 100000,
"Years": [
{
"Year": 2008,
"Monthly": [
{
"Month": 1,
"Count1": 49,
"Count2": 2
},
{
"Month": 2,
"Count1": 45,
"Count2": 1
},
.
.
.
]
},
{
"Year": 2009,
"Monthly": [
{
"Month": 1,
"Count1": 36,
"Count2": 1
},
{
"Month": 2,
"Count1": 33,
"Count2": 0
},
.
.
.
]
},
.
.
.
.
]
}
将始终针对单个 EntityId 查询此表。
我无法嵌套我的数组,年份也在重复(年份重复的次数是当年的月数,所以如果我有 2008 年的 12 个月数据,那么今年的数据重复 12 次)当我尝试以下查询时:
select f.EntityId,
(
select TOP 1 [year] as [year],
(
select [month] as [month],
[count1] as [count1],
[count2] as [count2],
from someTable m
where m.EntityId = f.EntityId and m.Year = y.Year
for json path
) as [months]
from someTable y
where y.EntityId = f.EntityId and y.Year = f.Year
for json path
) AS years
from someTable f
where f.EntityId = f.EntityId
for json path
【问题讨论】:
-
根据问题指南,请不要发布代码、数据、错误消息等的图像 - 将文本复制或键入问题中。请保留将图像用于图表或演示渲染错误,无法通过文本准确描述的事情。
标签: json sql-server tsql sql-server-2016