# SwiftData Aggregate

**URL:** <https://forums.swift.org/t/swiftdata-aggregate/66968>\
**Category:** Using Swift\
**Tags:** database-swiftdata\
**Created:** [August 26, 2023, 6:38pm UTC](https://forums.swift.org/t/swiftdata-aggregate/66968 "2023-08-26T18:38:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![AaronLBratcher](https://avatars.discourse-cdn.com/v4/letter/a/a3d4f5/32.png) [@AaronLBratcher](https://forums.swift.org/u/AaronLBratcher)\
**Post date:** [August 26, 2023, 6:38pm UTC](https://forums.swift.org/t/swiftdata-aggregate/66968/1 "2023-08-26T18:38:37Z")

</div>

Given a simple class:

```swift
final class Person {
   name: String
   age: Int
}

```

How can I get aggregated data such as average age, or count of people within specific ranges?

---

<div class="post-metadata">

**Author:** ![aggie33](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/aggie33/32/29896_2.png) [@aggie33](https://forums.swift.org/u/aggie33)\
**Post date:** [August 26, 2023, 6:51pm UTC](https://forums.swift.org/t/swiftdata-aggregate/66968/2 "2023-08-26T18:51:59Z")

</div>

If you have, say:

```swift
@Query var people: [Person]

```

Then you can get average age like this:

```swift
people.lazy.map(\.age).reduce(0) { $0 + Double($1) } / people.count

```

And you can get the number of people within an age range like this:

```swift
people.lazy.filter { range.contains($0.age) }.count

```

Hope that helps.

---

<div class="post-metadata">

**Author:** ![AaronLBratcher](https://avatars.discourse-cdn.com/v4/letter/a/a3d4f5/32.png) [@AaronLBratcher](https://forums.swift.org/u/AaronLBratcher)\
**Post date:** [August 26, 2023, 6:56pm UTC](https://forums.swift.org/t/swiftdata-aggregate/66968/3 "2023-08-26T18:56:11Z")

</div>

I was hoping to do it at the database level, not my code level. Thanks for the information, definitely helpful if I can't do it at the database level.
