# Window functions
source: https://docs.chalk.ai/docs/chalkdf/expressions/windows

## Order transactions within a group to compare neighboring values, rank rows, and compute running totals.

A window evaluates a calculation over related rows and appends the result to each transaction. Choose a partition key for independent histories and an ordering key that specifies the sequence within each history.

### Read the next value within a partition

To look ahead by one purchase, partition by user and sort by sequence. Use a negative shift to read the following value.

```python
from chalk import _, functions as F
from chalkdf import DataFrame

tx = DataFrame({
    "sequence": [1, 2, 3, 4], "user": ["a", "a", "b", "a"],
    "amount": [12, 8, 30, 8],
})

from libchalk.chalktable import WindowExpr

tx.window(
    ["user"], ["sequence"], WindowExpr.shift("amount", "next_amount", -1)
).order_by("sequence").run()
```

| sequence · `int64` | user · `string` | amount · `int64` | next_amount · `int64` |
| ------------------ | --------------- | ---------------- | --------------------- |
| 1                  | a               | 12               | 8                     |
| 2                  | a               | 8                | 8                     |
| 3                  | b               | 30               | null                  |
| 4                  | a               | 8                | null                  |

The transaction for b cannot supply a value for a. The last transaction for each user has a null next amount.

### Compare with a previous transaction

Reverse the shift to read the preceding amount, then calculate a change from it.

```python
history = tx.window(
    ["user"], ["sequence"], WindowExpr.shift("amount", "previous", 1)
)
history.project({
    "sequence": _.sequence, "user": _.user, "change": _.amount - _.previous,
}).order_by("sequence").run()
```

| sequence · `int64` | user · `string` | change · `int64` |
| ------------------ | --------------- | ---------------- |
| 1                  | a               | null             |
| 2                  | a               | -4               |
| 3                  | b               | null             |
| 4                  | a               | 0                |

The first change per user is unknown. The final change for a is zero because both adjacent amounts are 8.

### Rank purchases within a user

Rank by amount to identify the largest purchases per user. Rows tied on amount share a standard rank. Sort by sequence separately to display the original transaction history.

```python
tx.with_columns(
    F.over(F.rank(), partition_by="user", order_by=[("amount", "desc")]).alias("amount_rank")
).order_by("sequence").run()
```

| sequence · `int64` | user · `string` | amount · `int64` | amount_rank · `int64` |
| ------------------ | --------------- | ---------------- | --------------------- |
| 1                  | a               | 12               | 1                     |
| 2                  | a               | 8                | 2                     |
| 3                  | b               | 30               | 1                     |
| 4                  | a               | 8                | 2                     |

To identify one specific row among equal amounts, order by a unique tie-breaker and use a row number. Choosing a tie-breaker changes which row wins.

### Build a running total

Order the window by sequence and sum from the first row of the partition through the current row.

```python
tx.with_columns(
    F.over(_.amount.sum(), partition_by="user", order_by="sequence",
           frame=F.rows_between(None, 0)).alias("running_spend")
).order_by("sequence").run()
```

| sequence · `int64` | user · `string` | amount · `int64` | running_spend · `int64` |
| ------------------ | --------------- | ---------------- | ----------------------- |
| 1                  | a               | 12               | 12                      |
| 2                  | a               | 8                | 20                      |
| 3                  | b               | 30               | 30                      |
| 4                  | a               | 8                | 28                      |

The running total for a resumes after the intervening purchase for b. A grouped sum gives one final total per user instead.

### Limit a frame to the last two purchases

Use a bounded row frame for a moving total. A start of -1 includes one preceding row, and an end of 0 includes the current row.

```python
tx.with_columns(
    F.over(
        _.amount.sum(), partition_by="user", order_by="sequence",
        frame=F.rows_between(-1, 0),
    ).alias("last_two"),
).order_by("sequence").run()
```

| sequence · `int64` | user · `string` | amount · `int64` | last_two · `int64` |
| ------------------ | --------------- | ---------------- | ------------------ |
| 1                  | a               | 12               | 12                 |
| 2                  | a               | 8                | 20                 |
| 3                  | b               | 30               | 30                 |
| 4                  | a               | 8                | 16                 |

The final total for a is 16 across the last two purchases, compared with 28 across its whole history. A row frame measures a number of observations. The elapsed time between those observations can vary.

### Attach a group total to every purchase

Use a partition with no ordering to compute a total across the whole user history. Attach it to each purchase to calculate its share of spend.

```python
by_user = tx.with_columns(
    F.over(_.amount.sum(), partition_by="user").alias("user_total")
)
by_user.project({
    "sequence": _.sequence, "amount": _.amount, "user_total": _.user_total,
    "percent": F.round(_.amount * 100 / _.user_total, 1),
}).order_by("sequence").run()
```

| sequence · `int64` | amount · `int64` | user_total · `int64` | percent · `double` |
| ------------------ | ---------------- | -------------------- | ------------------ |
| 1                  | 12               | 28                   | 42.9               |
| 2                  | 8                | 28                   | 28.6               |
| 3                  | 30               | 30                   | 100.0              |
| 4                  | 8                | 28                   | 28.6               |

The group total repeats on each purchase. A grouped aggregation would collapse the three purchases by a into one row.

See [aggregations](/docs/chalkdf/expressions/aggregations) and [DataFrame.window](/dataframe-docs#DataFrame.window).





