Group By
Master SQL GROUP BY operations in TypeScript with tSQL's strongly-typed groupBy() method. Learn to aggregate data, create summary reports, and perform complex grouping operations with type safety and IntelliSense support.
The groupBy
clause groups rows that have the same values into summary rows. It's typically used with aggregate functions like count
, sum
, or avg
.
Basic Grouping
db.selectFrom("orders")
.select(["category", (eb) => eb.fn.count("id").as("total_orders")])
.groupBy("category")
.execute();
Multiple Columns
db.selectFrom("orders")
.select([
"category",
"status",
(eb) => eb.fn.sum("amount").as("total_amount"),
])
.groupBy(["category", "status"])
.execute();
SQL Expressions
import { sql } from "kysely";
db.selectFrom("sales")
.select([
(eb) => eb.fn.count("id").as("sales_count"),
sql`date_trunc('month', created_at)`.as("month"),
])
.groupBy(sql`date_trunc('month', created_at)`)
.execute();