0

我有嵌套的 JSON 文件,我试图将其用作报告的数据源。我正在“扁平化”结构,但不确定如何评估兄弟姐妹的数据。

样本数据:

{
"Cources": [{
        "ID": 1,
        "Name": "MAC100",
        "Room": 100,
        "TAID": 123,
        "StudentsIDs": [
            1, 2
        ]
    }
],

"TAs": [{
    "ID": 123,
    "Name": "Joe",
    "LName": "Smith"
}],

"Students": [{
    "ID": 1,
    "LName": "Clark"
}, {
    "ID": 2,
    "LName": "Peterson"
}]
 }

SQL Server:摄取数据文件并展平报告数据:

SELECT Cource.ID, 
Cource.Name as CName,
Cource.Room as CRoom,
CourceStudents.LName

FROM OPENROWSET (BULK 'C:\Data\file.json', SINGLE_CLOB) as jsonfile

CROSS APPLY OPENJSON(BulkColumn,'$[0]') WITH( 

   Cources nvarchar(max) AS JSON,
   TAs nvarchar(max) AS JSON,
   Students nvarchar(max) AS JSON

   ) AS [SampleData]

CROSS APPLY OPENJSON(Cources) WITH (
   Room integer,
   Name nvarchar(max),
   StudentsIDs nvarchar(max) AS JSON
)  as [Cources]

CROSS APPLY OPENJSON(Students) WITH ( 
    ID integer,
    LName nvarchar(max),
) as [Students]

CROSS APPLY OPENJSON(StudentsIDs) WITH ( 
 **//??? how to get full data for the student from "Students" joining by the student ID ?**
) as [CourceStudents]

我偶然发现如何将所有学生数据从“学生”获取到通过 ID 加入的“学生 ID”中。

4

1 回答 1

0

我创建了临时表,将 json 数据导入其中,这允许我有 WHERE 子句:

DROP TABLE IF EXISTS tempdb.dbo.#temp;
CREATE TABLE #temp (
 InfoJson nvarchar(max) 
) 

ALTER TABLE #temp
ADD CONSTRAINT [Content should be formatted as JSON]
 CHECK (ISJSON(InfoJson)> 0)

 Insert INTO #temp (InfoJson)
 SELECT *
 FROM OPENROWSET (BULK 'C:\Data\file.json', SINGLE_CLOB) as j;

SELECT Cource.ID, 
Cource.Name as CName,
Cource.Room as CRoom,
CourceStudents.LName  
FROM #temp

CROSS APPLY OPENJSON(InfoJson,'$') WITH( 
   Cources nvarchar(max) AS JSON,
   TAs nvarchar(max) AS JSON,
   Students nvarchar(max) AS JSON
   ) AS [SampleData]

CROSS APPLY OPENJSON(Cources) WITH (
   Room integer,
   Name nvarchar(max),
   StudentsIDs nvarchar(max) AS JSON
)  as [Cources]

CROSS APPLY OPENJSON(StudentsIDs) WITH (
     value nvarchar(100) '$'
) as [StudentsIDs]

CROSS APPLY OPENJSON(Students) WITH ( 
    ID integer,
    LName nvarchar(max),
) as [Students]

WHERE StudentsIDs.value=Students.ID
于 2017-02-15T15:47:21.750 回答