跳到主要内容
翻译页面

本页面由 AI 辅助从英文翻译而来。如两者存在差异,以英文版本为准。

COUNT

返回资源中的记录总数,或分组中某列非 NULL 实例的计数。

另请参阅:
[SELECT]


语法​

SELECT COUNT( * | columnExpression ) FROM <multipartIdentifier>
[ GROUP BY groupByColumn ];

参数​

columnExpression 或 *
列或表达式。如果指定 *,则统计资源或分组中的所有记录。

columnExpression 中的 NULL 值不计入计数。如果所有值都是 NULL,COUNT 返回 0。

groupByColumn
用于执行汇总或聚合操作的一列或多列。GROUP BY 子句为每个列分组返回一行。

返回值​

返回一个整数,表示计数。


示例​

返回整个资源的行数​

SELECT count(*) as num_instances
FROM google.compute.instances
WHERE project = 'stackql-demo'
AND zone = 'australia-southeast1-a';

返回按列表达式分组的行数​

SELECT SPLIT_PART(machineType, '/', -1) as machine_type, count(*) as num_instances
FROM google.compute.instances
WHERE project = 'stackql-demo'
AND zone = 'australia-southeast1-a'
GROUP BY SPLIT_PART(machineType, '/', -1);

将 COUNT 用作窗口函数来计算累计计数​

-- Track cumulative issue counts over time
SELECT
number,
title,
state,
created_at,
COUNT(*) OVER (ORDER BY created_at) as cumulative_issues,
COUNT(*) OVER (PARTITION BY state ORDER BY created_at) as cumulative_by_state
FROM github.issues.issues
WHERE owner = 'stackql'
AND repo = 'stackql'
ORDER BY created_at;

有关更多信息,请参阅 https://www.sqlite.org/lang_aggfunc.html#count。