Grouping
This page shows how to group records and compute aggregates (sums, counts, maximums…), and how to filter the groups with having. The SQL shown is the one generated for MySQL.
You do not declare the grouping: λORM deduces it when the query uses an aggregate function. The records are grouped by the properties returned that are not inside an aggregate function.
Aggregate functions
| Function | Description |
|---|---|
| avg | Calculates the average of the values in a group. |
| count | Counts the records in a group. |
| first | Returns the first value in a group. |
| last | Returns the last value in a group. |
| max | Calculates the maximum. |
| min | Calculates the minimum. |
| sum | Calculates the sum. |
Sum with filter and sort
Reads, for the orders of a customer, the order date and the total (sum of quantity × unit price), sorted by total in descending order. The records are grouped by order, the only property returned that is not an aggregate.
Lambda:
Orders.details
.filter(p => p.order.customer.name == customerName)
.map(p => ({ order: p.order.orderDate, total: sum(p.quantity * p.unitPrice) }))
.sort(p => desc(p.total))
SQL Result:
SELECT o1.OrderDate AS `order`, SUM((o.Quantity * o.UnitPrice)) AS total
FROM `Order Details` o
INNER JOIN Orders o1 ON o1.OrderID = o.OrderID
INNER JOIN Customers c ON c.CustomerID = o1.CustomerID
WHERE c.CompanyName = ?
GROUP BY o1.OrderDate
ORDER BY total desc
Grouping and having
Reads the highest price of each category, considering the products with a price greater than 5 whose supplier is from a given country, or with fewer than 3 units in stock. Only the categories whose highest price is greater than 50 are returned, sorted by that price in descending order.
filter is applied to the records before grouping (WHERE); having is applied to the groups (HAVING).
Lambda:
Products
.filter(p => (p.price > 5 && p.supplier.country == country) || (p.inStock < 3))
.having(p => max(p.price) > 50)
.map(p => ({ category: p.category.name, largestPrice: max(p.price) }))
.sort(p => desc(p.largestPrice))
SQL Result:
SELECT c.CategoryName AS category, MAX(p.UnitPrice) AS largestPrice
FROM Products p
INNER JOIN Suppliers s ON s.SupplierID = p.SupplierID
INNER JOIN Categories c ON c.CategoryID = p.CategoryID
WHERE ((p.UnitPrice > 5 AND s.Country = ?) OR p.UnitsInStock < 3)
GROUP BY c.CategoryName
HAVING MAX(p.UnitPrice) > 50
ORDER BY largestPrice desc
Code example
import { orm } from '@lambdaorm/lib'
import { Products } from './domain/model' // model generated by `lambdaorm build`
(async () => {
try {
await orm.init('./lambdaORM.yaml')
// highest price per category, for the categories whose highest price is greater than 50
const query = (country: string) => Products
.filter(p => (p.price > 5 && p.supplier.country == country) || (p.inStock < 3))
.having(p => max(p.price) > 50)
.map(p => ({ category: p.category.name, largestPrice: max(p.price) }))
.sort(p => desc(p.largestPrice))
const result = await orm.execute(query, { country: 'USA' })
console.log(JSON.stringify(result, null, 2))
} catch (error: any) {
console.error(error.stack)
} finally {
// releases the connections
await orm.end()
}
})()