【问题标题】:Count on CROSS APPLY with JSON Data依靠 JSON 数据的 CROSS APPLY
【发布时间】:2021-12-12 16:45:39
【问题描述】:

我有以下数据库结构:

ID、日期时间、JsonData

在 JsonData 中有一个名为 party 的字段,它是用 "," 分隔的,另一个字段名为 Source。

我正在尝试运行一个简单的选择,以获取按(来源、时间)分组的数据...

日期时间、来源、来源计数、计数方

2021 年 12 月 12 日,1、4、7

2021 年 12 月 12 日,2、3、5

我正在尝试运行以下 SQL,但是,我很难获得 CountParty。我总是倾向于得到 SourceCount。谁能解释一下我做错了什么?

我总是以

2021 年 12 月 12 日,1、4、4

2021 年 12 月 12 日,2、3、3

谢谢

select
json_value(JsonData,'$.Info.source') as Source
, Party.value
,count(json_value(JsonData,'$.Info.Party'))
,  count(*)

from test
CROSS APPLY 
    STRING_SPLIT(json_value(JsonData,'$.Info.Party'), ',') Party
group by json_value(JsonData,'$.Info.Source'), value
order by [Source]

{ "cID": "CID1","Info": {"Party": "A,B,C","Source" : "1"}}
{ "cID": "CID2","Info": {"Party": "A, C","Source" : "2" }}
{ "cID": "CID3","Info": {"Party": "B, C","Source" : "2" }}
{ "cID": "CID4","Info": {"Party": "B","Source" : "1" }}
{ "cID": "CID5","Info": {"Party": "C,A","Source" : "1" }}
{ "cID": "CID6","Info": {"Party": "A","Source" : "1" }}
{ "cID": "CID7","Info": {"Party": "C","Source" : "2" }}


select


json_value(JsonData,'$.Info.source') as Source

, Party.value

,count(json_value(JsonData,'$.Info.Party'))

,  count(*)


from test

CROSS APPLY 

    STRING_SPLIT(json_value(JsonData,'$.Info.Party'), ',') Party

group by json_value(JsonData,'$.Info.Source'), value

order by [Source]

【问题讨论】:

    标签: json sql-server cross-apply


    【解决方案1】:

    您的问题是因为您也是按value 分组的,它指的是STRING_SPLIT 中的value。因此,您会为每个单独的拆分 party 值获得一个新组。您应该将其从分组中删除。相反,您可以在子查询中获取Party 值的计数,然后是SUM

    还要注意,count(json_value(JsonData,'$.Info.Party')) 不计算不同的值,它计算有多少非空值,这可能不是您的意图。

    您也可以使用OPENJSON 一次提取所有值,而不是一次又一次地使用JSON_VALUE

    SELECT
      t.Datetime,
      j.Source,
      COUNT(*) SourceCount,
      SUM(p.PartyCount) PartyCount
    FROM test t
    CROSS APPLY
      OPENJSON(t.JsonData, '$.Info')
      WITH (
        Party nvarchar(500),
        Source nvarchar(100)
      ) j
    CROSS APPLY (
        SELECT COUNT(*) PartyCount
        FROM STRING_SPLIT(j.Party, ',')
    ) p
    group by
      t.Datetime,
      j.Source
    order by
      j.Source;
    

    【讨论】:

    • 谢谢。那成功了。我需要研究 OPENJSON... 看起来很强大。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 2017-07-24
    • 2019-09-07
    • 2013-07-08
    相关资源
    最近更新 更多