メインコンテンツまでスキップ

count

count

説明

式で指定された行の合計数を返します。

この関数には3つのバリエーションがあります:

  • COUNT(*) は、NULL値を含むかどうかに関係なく、テーブル内のすべての行をカウントします。
  • COUNT(expr) は、特定の列の非NULL値を持つ行の数をカウントします。
  • COUNT(DISTINCT expr) は、列の非NULL値の異なる数をカウントします。

COUNT(DISTINCT expr)は、正確な重複カウントに使用されます。より高速な重複カウントが必要な場合は、Use bitmap for exact count discountを参照してください。

StarRocks 2.4以降では、1つのステートメントで複数のCOUNT(DISTINCT)を使用できます。

構文

COUNT(expr)
COUNT(DISTINCT expr [,expr,...])`

パラメータ

exprcount()が実行される列または式。 exprが列名の場合、列は任意のデータ型である場合があります。

戻り値

数値値が返されます。行が見つからない場合、0が返されます。この関数はNULL値を無視します。

testという名前のテーブルがあると仮定します。 idで各注文の国名、カテゴリー、サプライヤーをクエリする。

select * from test order by id;
+------+----------+----------+------------+
| id | country | category | supplier |
+------+----------+----------+------------+
| 1001 | US | A | supplier_1 |
| 1002 | Thailand | A | supplier_2 |
| 1003 | Turkey | B | supplier_3 |
| 1004 | US | A | supplier_2 |
| 1005 | China | C | supplier_4 |
| 1006 | Japan | D | supplier_3 |
| 1007 | Japan | NULL | supplier_5 |
+------+----------+----------+------------+

例1: テーブルtest内の行数をカウントします。

    select count(*) from test;
+----------+
| count(*) |
+----------+
| 7 |
+----------+

例2: id列の値の数をカウントします。

    select count(id) from test;
+-----------+
| count(id) |
+-----------+
| 7 |
+-----------+

例3: NULL値を無視して category 列の値の数をカウントします。

select count(category) from test;
+-----------------+
| count(category) |
+-----------------+
| 6 |
+-----------------+

例4: category 列の異なる値の数をカウントします。

select count(distinct category) from test;
+-------------------------+
| count(DISTINCT category) |
+-------------------------+
| 4 |
+-------------------------+

例5: categorysupplier で形成される組み合わせの数をカウントします。

select count(distinct category, supplier) from test;
+------------------------------------+
| count(DISTINCT category, supplier) |
+------------------------------------+
| 5 |
+------------------------------------+

出力結果では、idが1004の組み合わせはidが1002の組み合わせと重複しています。 それらは1回だけカウントされます。idが1007の組み合わせはNULL値を持ち、カウントされません。

例6: 1つのステートメントで複数のCOUNT(DISTINCT)を使用します。

select count(distinct country, category), count(distinct country,supplier) from test;
+-----------------------------------+-----------------------------------+
| count(DISTINCT country, category) | count(DISTINCT country, supplier) |
+-----------------------------------+-----------------------------------+
| 6 | 7 |
+-----------------------------------+-----------------------------------+