azure 如何使用cosmos db处理group by查询中缺少的字段?

vngu2lb8  于 2023-06-24  发布在  其他
关注(0)|答案(1)|浏览(106)

我需要使用Group By与Cosmos DB数据集。

SELECT
    GroupedField1,
    GroupedField2,
    COUNT(1) AS GroupCount
FROM
    YourCollection
GROUP BY
    GroupedField1,
    GroupedField2;

但是GroupedField2可以为null或者在某些文档上不存在。如何用cosmos db在group by query中处理此类缺失字段。

dy2hfwbg

dy2hfwbg1#

代码

SELECT
c.GroupedField1,
IS_DEFINED(c.GroupedField2) ? c.GroupedField2 : null  as GroupedField2,
COUNT(1) AS GroupCount
FROM
c
GROUP  BY
c.GroupedField1,
IS_DEFINED(c.GroupedField2) ? c.GroupedField2 : null

该查询将c容器中的文档按GroupedField1GroupedField2分组,并计算每个组中的文档数。如果缺少GroupedField2null,则在分组时将其替换为null
尝试此代码与样本输入和下面是结果。输入

{
    "id": "1",
    "GroupedField1": "A",
    "GroupedField2": "X"
},
{
    "id": "2",
    "GroupedField1": "A",
    "GroupedField2": "Y"
},
{
    "id": "3",
    "GroupedField1": "B",
    "GroupedField2": null
},
{
    "id": "4",
    "GroupedField1": "B"
}

输出:

[
    {
        "GroupedField1": "B",
        "GroupedField2": null,
        "GroupCount": 2
    },
    {
        "GroupedField1": "A",
        "GroupedField2": "Y",
        "GroupCount": 1
    },
    {
        "GroupedField1": "A",
        "GroupedField2": "X",
        "GroupCount": 1
    }
]

相关问题