如何在 CosmosDB SQL-API 中按 day/month/year 分组

How to group by day/month/year in CosmosDB SQL-API

我想创建一个函数,能够根据日、月或年对我在 Cosmos DB 上的数据进行分组。我已经在 pandas 中有一个执行命令。我也想这样做。

df = pd.DataFrame(
    [
    {'date': '27/06/2020 12:49', 'labels': 0, 'code': 1},
    {'date': '27/06/2020 17:10', 'labels': 0, 'code': 3},
    {'date': '22/06/2020 09:02', 'labels': 0, 'code': 3},
    {'date': '22/06/2020 10:38', 'labels': 1, 'code': 1},
    {'date': '22/06/2020 21:50', 'labels': 1, 'code': 3},
    {'date': '25/06/2020 00:46', 'labels': 1, 'code': 1}
    ]
)

df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y %H:%M')
df.groupby(pd.Grouper(key='date',freq='D')).agg({'label':'sum', 'code':'count'})

我已经在 Cosmos 中尝试了不同的方法,但结果很奇怪。这是我的查询和相应的结果:

'SELECT DateTimePart("D", r.data_ora_inserimento_preventivo), r.labels, r.sorgente_dati, count(1) FROM mycontainer r group by DateTimePart("D", r.data_ora_inserimento_preventivo), r.labels, r.sorgente_dati'

{'labels': 0, 'code': '3', '': 16236}
{'labels': 1, 'code': '3', '': 286}
{'labels': 0, 'code': '3', '': 16534}
{'labels': 1, 'code': '3', '': 187}
{'labels': 0, 'code': '3', '': 15726}
{'labels': 1, 'code': '3', '': 161}
{'labels': 0, 'code': '3', '': 15854}
{'labels': 1, 'code': '3', '': 177}
{'labels': 0, 'code': '3', '': 15405}
{'labels': 1, 'code': '3', '': 164}
{'labels': 0, 'code': '3', '': 15723}
{'labels': 1, 'code': '3', '': 304}
{'labels': 1, 'code': '3', '': 447}
{'labels': 0, 'code': '3', '': 3012}

DateTimePart will return undefined for the following reasons:

The DateTimePart value specified is invalid

The DateTime is not a valid ISO 8601 DateTime

您的日期不是有效的 ISO 8601 日期时间,这会导致出现奇怪的结果。因此,您需要将日期转换为 ISO 格式。您可以通过 UDF 实现此目的。然后尝试这样的事情 SQL:

SELECT 
    left(udf.casttoISO(c.date),10) as date, sum(c.labels) as labels, count(c.code) as code 
FROM c 
group by left(udf.casttoISO(c.date),10) 

结果:

[
    {
        "date": "2020-06-25",
        "labels": 1,
        "code": 1
    },
    {
        "date": "2020-06-22",
        "labels": 2,
        "code": 3
    },
    {
        "date": "2020-06-27",
        "labels": 0,
        "code": 2
    }
]

顺便说一句,DateTimePart函数不会利用索引,所以我认为Left函数会更好。


更新:

1.You 可以在 Portal 中创建 UDF。关于UDF,可以参考这个MSDN

2.Your 评论提到您正在使用 Python SDK。不幸的是,当你运行上面的SQL时,你会得到以下错误信息:

(BadRequest) Gateway Failed to Retrieve Query Plan: Query contains 1 or more unsupported features. Upgrade your SDK to a version that does support the requested features: Query contained GroupBy, which the calling client does not support.

因为Python SDK 目前不支持Group BY。他们计划在今年添加此功能。可以参考this。如果你想执行以上SQL,你可以运行在Portal,使用.NET SDK或JS SDK。