Couchbase N1QL 查询聚合

Couchbase N1QL query aggregation

我正在尝试编写一个查询,该查询将聚合查询结果以提供匹配结果的总值。

存储桶中的文档如下所示:

{
    "clientId": "test-client",
    "event": {
        "history": [
            {
                "code": "FAILED",
                "serviceId": "s1"
            },
            {
                "code": "SUCCESS",
                "serviceId": "s2"
            }
        ],
        "size": 200
    }
},
{
    "clientId": "test-client",
    "event": {
        "history": [
            {
                "code": "FAILED",
                "serviceId": "s1"
            },
            {
                "code": "SUCCESS",
                "serviceId": "s2"
            }
        ],
        "size": 200
    }
},
{
    "clientId": "test-client",
    "event": {
        "history": [
            {
                "code": "SUCCESS",
                "serviceId": "s1"
            }
        ],
        "size": 200
    }
}

我要生成的输出文档如下所示:

{
    "clientId": "test-client",
    "totalSize": 600,
    "totalVolume": 3,
    "serviceSummary": [
        {
            "serviceId": "s1",
            "serviceTotalSize": 200,
            "serviceTotalVolume": 1
        },
        {
            "serviceId": "s2",
            "serviceTotalSize": 400,
            "serviceTotalVolume": 2
        }
    ]
}

所以查询需要

到目前为止,我有这样的查询:

select 
    d.clientId, 
    count(*) totalVolume, 
    sum(d.event.size) totalSize ,
    ARRAY_AGG(DISTINCT h.serviceId) serviceSummary
from demo d
unnest d.event.history h
where h.code = 'SUCCESS'
group by d.clientId;

它产生了我想要的部分结果,但不是完整的 serviceSummary

感谢您的帮助。

SQL 标准不允许嵌套聚合,您需要使用多级聚合干预子查询。

SELECT d1.clientId,
       SUM(d1.serviceTotalVolume) AS totalVolume,
       SUM(d1.serviceTotalSize) AS totalSize,
       ARRAY_AGG({d1.serviceId, d1.serviceTotalVolume, d1.serviceTotalSize}) AS serviceSummary
FROM ( SELECT
             d.clientId,
             h.serviceId,
             COUNT(1) AS serviceTotalVolume,
             SUM(d.event.size) AS serviceTotalSize
       FROM demo AS d
       UNNEST d.event.history AS h
       WHERE h.code = 'SUCCESS'
       GROUP BY d.clientId, h.serviceId) AS d1
GROUP BY d1.clientId;