> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> 使用输出格式对每个组中的行进行格式化，并将格式化后的数据作为字符串返回。

# groupFormat

使用输出格式对每个组中的行进行格式化，并将格式化后的数据作为字符串返回。这与 `formatRow` 类似，但它作用于整个组，并且可以使用基于块的格式。

<Warning>
  在生成格式化字符串之前，每个组的所有行都会先累积在内存中。对于行数非常多的组，这可能会消耗大量内存。请考虑在子查询中使用 `LIMIT`，或拆分大型组，以便将内存使用量控制在可接受范围内。
</Warning>

<div id="syntax">
  ## 语法
</div>

```sql theme={null}
groupFormat(format)(x, y, ...)
```

<div id="parameters">
  ## 参数
</div>

* `format` — 输出格式名称，例如 `JSONEachRow`、`CSV`、`TabSeparated`。

<div id="arguments">
  ## 实参
</div>

* `x, y, ...` — 将格式化为行的表达式。至少需要一个参数。

<div id="returned-value">
  ## 返回值
</div>

* 一个 [String](/docs/zh/reference/data-types/string)，包含该分组的格式化输出。

<Note>
  格式化输出中的列名会按照参数顺序生成为 `c1`、`c2`、……。

  格式化后各行的具体顺序不保证固定。

  查询的格式设置 (例如 `format_csv_delimiter` 或 `output_format_json_quote_64bit_integers`) 会在聚合函数初始化时被记录下来，并用于生成输出。`output_format_write_statistics` 设置始终会被强制关闭，因此格式化字符串中绝不会包含统计信息部分。
</Note>

<div id="null-handling">
  ## NULL 处理
</div>

与 `groupArray` 和 `groupConcat` 一样，如果 `groupFormat` 的任一参数为 `NULL`，则会跳过该行；这类行不会出现在格式化输出中。当参数为 Nullable 类型时，结果类型为 `Nullable(String)`；而对于所有行都被跳过的分组，以及类型为 `Nullable(Nothing)` 的无类型字面量 `NULL` 参数，都会通过通用的 `Null` 组合器返回 `NULL`。

```sql theme={null}
SELECT groupFormat('JSONEachRow')(if(number = 0, NULL, number))
FROM numbers(3);
-- {"c1":1}
-- {"c1":2}
```

<div id="examples">
  ## 示例
</div>

<div id="example-json">
  ### JSONEachRow 的基础用法
</div>

```sql theme={null}
SELECT groupFormat('JSONEachRow')(number, toString(number))
FROM numbers(3);
```

结果：

```text theme={null}
{"c1":0,"c2":"0"}
{"c1":1,"c2":"1"}
{"c1":2,"c2":"2"}
```

<div id="groupFormat">
  ## groupFormat
</div>

Introduced in：v

使用指定的输出格式对每个分组中的行进行格式化，并将结果作为字符串返回。

格式名称作为参数传入，要格式化的列则作为 arguments 传入。
在格式化后的输出中，列名会生成为 c1、c2、...。

**语法**

```sql theme={null}
groupFormat(format)(x, y, ...)
```

**参数**

* `format` — 输出格式名称。例如，JSONEachRow、CSV、TabSeparated。[`String`](/docs/zh/reference/data-types/string)

**实参**

* `x, y, ...` — 要格式化为行的表达式。[`Any`](/docs/zh/reference/data-types/index)

**返回值**

该分组的格式化输出。[`String`](/docs/zh/reference/data-types/string)

**示例**

**基本用法**

```sql title=Query theme={null}
SELECT groupFormat('JSONEachRow')(number, toString(number))
FROM numbers(3)
```

```response title=Response theme={null}
{"c1":0,"c2":"0"}
{"c1":1,"c2":"1"}
{"c1":2,"c2":"2"}
```
