Aggregation, grouping, and summarizing[Prisma]

SnowCat·2023년 5월 25일
0

Prisma

목록 보기
9/10
post-thumbnail

Aggregate

  • aggregate 메서드를 사용해 데이터 테이블 값의 합, 차, 평균, 최대, 최소를 구할 수 있음
const aggregations = await prisma.user.aggregate({
  _avg: {
    age: true,
  },
})

console.log('Average age:' + aggregations._avg.age)

// 다른 조건을 결합할 수도 있음
const aggregations = await prisma.user.aggregate({
  _avg: {
    age: true,
  },
  where: {
    email: {
      contains: 'prisma.io',
    },
  },
  orderBy: {
    age: 'asc',
  },
  take: 10,
})

console.log('Average age:' + aggregations._avg.age)
  • 기본적으로 null값을 제외하고 계산해주나, 모든값이 null이거나 값이 없으면 null을 반환할수도 있음
const aggregations = await prisma.user.aggregate({
  _avg: {
    age: true,
  },
  _count: {
    age: true,
  },
})

/*
{
  _avg: {
    age: null
  },
  _count: {
    age: 9
  }
}
*/

Group By

  • groupBy 메서드를 사용해 group by 쿼리를 수행할 수 있음
const groupUsers = await prisma.user.groupBy({
  by: ['country'],
  _sum: {
    profileViews: true,
  },
})

/*
;[
  { country: 'Germany', _sum: { profileViews: 126 } },
  { country: 'Sweden', _sum: { profileViews: 0 } },
]
*/
  • 쿼리 진행 시 where절과 having절을 사용 가능
// where절로 groupBy의 대상을 좁힐 수 있음
const groupUsers = await prisma.user.groupBy({
  by: ['country'],
  where: {
    email: {
      contains: 'prisma.io',
    },
  },
  _sum: {
    profileViews: true,
  },
})

// having절을 사용해 group by로 얻어진 데이터 하나하나를 필터링 할 수 있음
const groupUsers = await prisma.user.groupBy({
  by: ['country'],
  where: {
    email: {
      contains: 'prisma.io',
    },
  },
  _sum: {
    profileViews: true,
  },
  having: {
    profileViews: {
      _avg: {
        gt: 100,
      },
    },
  },
})
  • group by를 사용한 데이터에도 order by절을 사용할 수 있음
const groupBy = await prisma.user.groupBy({
  by: ['city'],
  _count: {
    city: true,
  },
  orderBy: {
    _count: {
      city: 'desc',
    },
  },
})

Count

  • count 메서드를 사용하면 조건을 만족하는 데이터의 개수를 얻을 수 있음
const userCount = await prisma.user.count()
  • 만약 관계 필드의 count값을 반환하고싶다면 _count 옵션 사용
    include, select 옵션 내부에 사용 가능하며, 레코드를 반환하는 메서드라면 어디에서던지 사용 가능
const usersWithCount = await prisma.user.findMany({
  include: {
    _count: {
      select: { posts: true },
    },
  },
})
  • 필드 여러개의 count를 동시에 가져올수도 있음
const usersWithCount = await prisma.user.findMany({
  select: {
    _count: {
      select: {
        posts: true,
        recipes: true,
      },
    },
  },
})
  • count절을 수행할 때 조건에 맞는 필드만 쿼리할수도 있음
// Count all user posts with the title "Hello!"
await prisma.user.findMany({
  select: {
    _count: {
      select: {
        posts: { where: { title: 'Hello!' } },
      },
    },
  },
})
  • 특정 필드의 null 여부를 거르고 싶을때에는 property: true 옵션을 사용
    _all: true 사용시 모든 레코드를 반환함
const userCount = await prisma.user.count({
  select: {
    _all: true, // Count all records
    name: true, // Count all non-null field values
  },
})

Select distinct

  • 필드의 중복을 방지할 때 distinct 옵션을 사용
    sql의 distince문을 사용하지 않고 받아온 쿼리를 prisma에서 필터링함
const result = await prisma.user.findMany({
  where: {},
  distinct: ['name'],
})

https://www.prisma.io/docs/concepts/components/prisma-client/aggregation-grouping-summarizing

profile
냐아아아아아아아아앙

0개의 댓글