> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-3a82795f.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> 最後に現れた値を選択します。`anyLast` に似ていますが、NULL も受け取れます。

# last_value

最後に現れた値を選択します。`anyLast` に似ていますが、NULL も受け取れます。
主に [Window Functions](/ja/reference/functions/window-functions) と組み合わせて使用します。
Window Functions を使用しない場合、ソースストリームに順序がなければ、結果はランダムになります。

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

```sql theme={null}
CREATE TABLE test_data
(
    a Int64,
    b Nullable(Int64)
)
ENGINE = Memory;

INSERT INTO test_data (a, b) VALUES (1,null), (2,3), (4, 5), (6,null)
```

<div id="example1">
  ### 例 1
</div>

NULL 値はデフォルトで無視されます。

```sql theme={null}
SELECT last_value(b) FROM test_data
```

```text theme={null}
┌─last_value_ignore_nulls(b)─┐
│                          5 │
└────────────────────────────┘
```

<div id="example2">
  ### 例 2
</div>

NULL 値は無視されます。

```sql theme={null}
SELECT last_value(b) ignore nulls FROM test_data
```

```text theme={null}
┌─last_value_ignore_nulls(b)─┐
│                          5 │
└────────────────────────────┘
```

<div id="example3">
  ### 例 3
</div>

NULL 値が許容されます。

```sql theme={null}
SELECT last_value(b) respect nulls FROM test_data
```

```text theme={null}
┌─last_value_respect_nulls(b)─┐
│                        ᴺᵁᴸᴸ │
└─────────────────────────────┘
```

<div id="example4">
  ### 例 4
</div>

`ORDER BY` を使ったサブクエリによる安定した結果。

```sql theme={null}
SELECT
    last_value_respect_nulls(b),
    last_value(b)
FROM
(
    SELECT *
    FROM test_data
    ORDER BY a ASC
)
```

```text theme={null}
┌─last_value_respect_nulls(b)─┬─last_value(b)─┐
│                        ᴺᵁᴸᴸ │             5 │
└─────────────────────────────┴───────────────┘
```
