使用一个 Cosmos DB 查询获取多个计数?
Get multiple counts with one Cosmos DB query?
考虑这些查询:
SELECT COUNT(1) AS failures
FROM c
WHERE c.time = 1623332779 AND c.status = 'FAILURE'
SELECT COUNT(1) AS successes
FROM c
WHERE c.time = 1623332779 AND c.status = 'SUCCESS'
如何将这两个不同的查询合并为一个查询?
我尝试重新利用 How to get multiple counts with one SQL query? 的答案,但 运行 变成了几个问题:
COUNT(*)
抛出错误“语法错误,‘*’附近的语法不正确。”
UNION
抛出“语法错误,'UNION' 附近的语法不正确”。
我也试过
SELECT
SUM(CASE WHEN c.time = 1623332779 THEN 1 else 0 end)
FROM c
但这会导致另一个语法错误。我注意到
SELECT COUNT(1) AS mycounter, COUNT(1) AS mycounter2
FROM c
WHERE c.time = 1623332779
returns
[
{
"mycounter": 3,
"mycounter2": 3
}
]
但我无法link这些不同的计数器来应对不同的查询。
以下应该有效。计数运算符会跳过 undefined
的值,这使您可以从中过滤掉行:
SELECT
COUNT(c.status = 'SUCCESS' ? 1 : undefined) AS successes,
COUNT(c.status = 'FAILURE' ? 1 : undefined) AS failures
FROM c
WHERE c.time = 1623332779
它会破坏性能,因为它根本不使用索引进行计数。所以你最好使用两个单独的查询。如果您真的想使用单个请求,您可以创建一个存储过程来运行两个查询并将结果粘贴在一起。
您可以使用 GROUP BY
在单个查询中获取计数,而不是对整个查询进行计数。例如:
SELECT c.time, c.status, COUNT(c.status) AS statuscount
FROM c
WHERE c.time = "1623332779"
GROUP BY c.time, c.status
这不会为您提供称为“成功”和“失败”的显式计数,但会 return 两种计数,例如:
[
{
"time": "1623332779",
"status": "FAILURE",
"statuscount": 123
},
{
"time": "1623332779",
"status": "SUCCESS",
"statuscount": 456
}
]
考虑这些查询:
SELECT COUNT(1) AS failures
FROM c
WHERE c.time = 1623332779 AND c.status = 'FAILURE'
SELECT COUNT(1) AS successes
FROM c
WHERE c.time = 1623332779 AND c.status = 'SUCCESS'
如何将这两个不同的查询合并为一个查询?
我尝试重新利用 How to get multiple counts with one SQL query? 的答案,但 运行 变成了几个问题:
COUNT(*)
抛出错误“语法错误,‘*’附近的语法不正确。”UNION
抛出“语法错误,'UNION' 附近的语法不正确”。
我也试过
SELECT
SUM(CASE WHEN c.time = 1623332779 THEN 1 else 0 end)
FROM c
但这会导致另一个语法错误。我注意到
SELECT COUNT(1) AS mycounter, COUNT(1) AS mycounter2
FROM c
WHERE c.time = 1623332779
returns
[
{
"mycounter": 3,
"mycounter2": 3
}
]
但我无法link这些不同的计数器来应对不同的查询。
以下应该有效。计数运算符会跳过 undefined
的值,这使您可以从中过滤掉行:
SELECT
COUNT(c.status = 'SUCCESS' ? 1 : undefined) AS successes,
COUNT(c.status = 'FAILURE' ? 1 : undefined) AS failures
FROM c
WHERE c.time = 1623332779
它会破坏性能,因为它根本不使用索引进行计数。所以你最好使用两个单独的查询。如果您真的想使用单个请求,您可以创建一个存储过程来运行两个查询并将结果粘贴在一起。
您可以使用 GROUP BY
在单个查询中获取计数,而不是对整个查询进行计数。例如:
SELECT c.time, c.status, COUNT(c.status) AS statuscount
FROM c
WHERE c.time = "1623332779"
GROUP BY c.time, c.status
这不会为您提供称为“成功”和“失败”的显式计数,但会 return 两种计数,例如:
[
{
"time": "1623332779",
"status": "FAILURE",
"statuscount": 123
},
{
"time": "1623332779",
"status": "SUCCESS",
"statuscount": 456
}
]