TSQL从JSON中选择基本分层数据

时间:2018-02-19 10:29:34

标签: json sql-server tsql

这是一个非常简单的问题,但我无法在任何地方找到一个单一的工作示例。 MSDN暗示可以(herehere),但是错过了实际示例,Google提供了大量从 TSQL输出JSON 的示例,而我需要反过来。

采用最基本的JSON结构:

DECLARE @json nvarchar(max) = N'[{
    "Id":       1,
    "name":     "John",
    "skills": [
        {"title":   "Azure" },
        {"title":   "VB" },
        {"title":   "JavaScript" }]
}, {
    "Id":       2,
    "name":     "Jane",
     "skills": [
        {"title":   "Azure" },
        {"title":   "SQL" },
        {"title":   "C#" }]
}]';

我想出了如何获得最高级别的值,例如Idname

SELECT
    *
FROM
    OPENJSON(@json) WITH (
    ID int '$.Id',
    name nvarchar(50) '$.name'
    );

我想要的是输出 PersonId ,以及各自的技能标题,例如

PersonId     SkillTitle
-----------------------
1            Azure
1            VB
1            JavaScript
2            Azure
2            SQL
2            C#

Google只为我提供了相反的逻辑。根据我能找到的内容,我严重破坏的尝试就在这里:

SELECT
    *
FROM
    OPENJSON(@json, '$.skills') WITH (
        PersonId int './Id',
        SkillTitle nvarchar(50) '$.title'
    );

1 个答案:

答案 0 :(得分:1)

以下代码段会为您提供所需的结果 -

Fatal Exception: java.lang.NoClassDefFoundError: ppn
   at ppm.(SourceFile:2)
   at ppk.onAnimationEnd(SourceFile:10)
   at android.animation.AnimatorSet$AnimatorSetListener.onAnimationEnd(AnimatorSet.java:765)
   at android.animation.ValueAnimator.endAnimation(ValueAnimator.java:1012)
   at android.animation.ValueAnimator.access$400(ValueAnimator.java:51)
   at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:623)
   at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:639)
   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
   at android.view.Choreographer.doCallbacks(Choreographer.java:579)
   at android.view.Choreographer.doFrame(Choreographer.java:547)
   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
   at android.os.Handler.handleCallback(Handler.java:800)
   at android.os.Handler.dispatchMessage(Handler.java:100)
   at android.os.Looper.loop(Looper.java:194)
   at android.app.ActivityThread.main(ActivityThread.java:5426)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
   at dalvik.system.NativeStart.main(NativeStart.java)

通过SELECT JSON_Value (c.value, '$.Id') as ID, JSON_Value (p.value, '$.title') as SkillTitle FROM OPENJSON (@json) as c CROSS APPLY OPENJSON(c.value,'$.skills') as p CROSS APPLY子节点与父节点并使用JSON函数实现了相同的功能。