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

# sumSimpleState

> sumSimpleState combinator를 사용하는 예시

<div id="description">
  ## 설명
</div>

[`SimpleState`](/ko/reference/functions/aggregate-functions/combinators#-simplestate) combinator는 [`sum`](/ko/reference/functions/aggregate-functions/sum)
함수에 적용할 수 있으며, 모든 입력 값의 합계를 반환합니다. 결과는
[`SimpleAggregateFunction`](/ko/reference/data-types/simpleaggregatefunction) 유형으로 반환됩니다.

<div id="example-usage">
  ## 사용 예시
</div>

<div id="tracking-post-votes">
  ### 추천 수와 비추천 수 추적
</div>

게시물의 투표를 추적하는 테이블을 사용하는 실용적인 예시를 살펴보겠습니다.
각 게시물별로 추천 수, 비추천 수, 그리고 전체 점수의 누적 합계를 유지하려고
합니다. 이 사용 사례에는 `SimpleAggregateFunction` 유형과 sum을 사용하는 방식이
적합합니다. 집계의 전체 상태가 아니라 누적 합계만 저장하면 되기 때문입니다.
따라서 더 빠르고, 부분 집계 상태를 병합할 필요도 없습니다.

먼저 원시 데이터용 테이블을 생성합니다:

```sql title="Query" theme={null}
CREATE TABLE raw_votes
(
    post_id UInt32,
    vote_type Enum8('upvote' = 1, 'downvote' = -1)
)
ENGINE = MergeTree()
ORDER BY post_id;
```

다음으로, 집계된 데이터를 저장할 대상 테이블을 생성합니다:

```sql theme={null}
CREATE TABLE vote_aggregates
(
    post_id UInt32,
    upvotes SimpleAggregateFunction(sum, UInt64),
    downvotes SimpleAggregateFunction(sum, UInt64),
    score SimpleAggregateFunction(sum, Int64)
)
ENGINE = AggregatingMergeTree()
ORDER BY post_id;
```

그다음 `SimpleAggregateFunction` 타입의 컬럼을 사용하는 materialized view를 생성합니다:

```sql theme={null}
CREATE MATERIALIZED VIEW mv_vote_processor TO vote_aggregates
AS
SELECT
  post_id,
  -- sum 상태의 초기값 (upvote이면 1, 그 외에는 0)
  toUInt64(vote_type = 'upvote') AS upvotes,
  -- sum 상태의 초기값 (downvote이면 1, 그 외에는 0)
  toUInt64(vote_type = 'downvote') AS downvotes,
  -- sum 상태의 초기값 (upvote이면 1, downvote이면 -1)
  toInt64(vote_type) AS score
FROM raw_votes;
```

샘플 데이터를 삽입하세요:

```sql theme={null}
INSERT INTO raw_votes VALUES
    (1, 'upvote'),
    (1, 'upvote'),
    (1, 'downvote'),
    (2, 'upvote'),
    (2, 'downvote'),
    (3, 'downvote');
```

`SimpleState` combinator를 사용해 materialized view를 쿼리합니다:

```sql theme={null}
SELECT
  post_id,
  sum(upvotes) AS total_upvotes,
  sum(downvotes) AS total_downvotes,
  sum(score) AS total_score
FROM vote_aggregates -- 대상 테이블 쿼리
GROUP BY post_id
ORDER BY post_id ASC;
```

```response theme={null}
┌─post_id─┬─total_upvotes─┬─total_downvotes─┬─total_score─┐
│       1 │             2 │               1 │           1 │
│       2 │             1 │               1 │           0 │
│       3 │             0 │               1 │          -1 │
└─────────┴───────────────┴─────────────────┴─────────────┘
```

<div id="see-also">
  ## 관련 항목
</div>

* [`sum`](/ko/reference/functions/aggregate-functions/sum)
* [`SimpleState combinator`](/ko/reference/functions/aggregate-functions/combinators#-simplestate)
* [`SimpleAggregateFunction 유형`](/ko/reference/data-types/simpleaggregatefunction)
