RingDotNetfor Ring

Reports with SQL

Databases are good at questions. This lesson asks them with SQL — JOIN to combine tables, GROUP BY to total, HAVING and WHERE to filter, LEFT JOIN to keep everybody, and a sub-query to compare with an average.

What you will learn#

The data#

Two tables (the tutorial Databases step by step explains how to create them): Customers (Ann and Cy in Cairo, Bob in Oslo, Dee in Tokyo) and Orders with a CustomerId that points to the customer, a product, an amount and a month. Dee has never ordered anything — that matters in step 4.

The program#

samples/UsingDotNet/tutorials/ch09_sql_reports.ring
# reports with SQL - JOIN, GROUP BY, HAVING, LEFT JOIN, sub-queries and parameters
load "dotnet.ring"

using { "RingDotNet.Data" }

func main

	aSchema = [
		["Customers",[["Id","int",1],["Name","string",0],["City","string",0]]],
		["Orders",[["Id","int",1],["CustomerId","int",0,[["references","Customers"]]],["Product","string",0],["Amount","int",0],["Month","string",0]]]
	]
	oDb = new RingDatabase("Data Source=:memory:",aSchema)
	nAnn = oDb.insert("Customers",[["Name","Ann"],["City","Cairo"]])
	nBob = oDb.insert("Customers",[["Name","Bob"],["City","Oslo"]])
	nCy = oDb.insert("Customers",[["Name","Cy"],["City","Cairo"]])
	nDee = oDb.insert("Customers",[["Name","Dee"],["City","Tokyo"]])
	for aOrder in [[nAnn,"Laptop",900,"Jan"],[nAnn,"Mouse",20,"Jan"],[nAnn,"Monitor",250,"Feb"],[nBob,"Laptop",950,"Jan"],[nBob,"Keyboard",60,"Mar"],[nCy,"Mouse",25,"Feb"],[nCy,"Mouse",25,"Mar"]]
		oDb.insert("Orders",[["CustomerId",aOrder[1]],["Product",aOrder[2]],["Amount",aOrder[3]],["Month",aOrder[4]]])
	next
	? "4 customers and " + oDb.count("Orders") + " orders are in the database (Dee has no orders)"

	# 1. JOIN: put the rows of two tables together where the keys are equal. Each order shows the name of its customer.
	? nl + "1. who bought what:"
	show(oDb.sqlRows("SELECT c.Name, o.Product, o.Amount FROM Orders o JOIN Customers c ON c.Id = o.CustomerId ORDER BY o.Id",[]),["Name","Product","Amount"])

	# 2. GROUP BY: one row per group, with an aggregate (SUM, COUNT, AVG, MIN, MAX) over each group
	? nl + "2. the total of each customer, the biggest first:"
	show(oDb.sqlRows("SELECT c.Name, COUNT(o.Id) AS Orders, SUM(o.Amount) AS Total FROM Customers c JOIN Orders o ON o.CustomerId = c.Id GROUP BY c.Name ORDER BY Total DESC",[]),["Name","Orders","Total"])

	# 3. WHERE filters the rows before they are grouped; HAVING filters the groups after
	? nl + "3. customers who spent more than 300 (HAVING):"
	show(oDb.sqlRows("SELECT c.Name, SUM(o.Amount) AS Total FROM Customers c JOIN Orders o ON o.CustomerId = c.Id GROUP BY c.Name HAVING SUM(o.Amount) > {0}",[300]),["Name","Total"])
	? "   the same for January only (WHERE first):"
	show(oDb.sqlRows("SELECT c.Name, SUM(o.Amount) AS Total FROM Customers c JOIN Orders o ON o.CustomerId = c.Id WHERE o.Month = {0} GROUP BY c.Name",["Jan"]),["Name","Total"])

	# 4. An inner JOIN drops customers without orders. LEFT JOIN keeps every row of the left table (the missing values are empty).
	? nl + "4. every customer with the number of orders (LEFT JOIN keeps Dee):"
	show(oDb.sqlRows("SELECT c.Name, COUNT(o.Id) AS Orders FROM Customers c LEFT JOIN Orders o ON o.CustomerId = c.Id GROUP BY c.Name ORDER BY c.Name",[]),["Name","Orders"])

	# 5. Group by a column of the other table: the total per city
	? nl + "5. the total per city:"
	show(oDb.sqlRows("SELECT c.City, SUM(o.Amount) AS Total FROM Customers c JOIN Orders o ON o.CustomerId = c.Id GROUP BY c.City ORDER BY Total DESC",[]),["City","Total"])

	# 6. A sub-query: the orders that are bigger than the average order
	? nl + "6. orders above the average (a sub-query calculates the average):"
	show(oDb.sqlRows("SELECT Product, Amount FROM Orders WHERE Amount > (SELECT AVG(Amount) FROM Orders) ORDER BY Amount DESC",[]),["Product","Amount"])

	# 7. A single value: scalar() returns the first column of the first row
	? nl + "7. the number of different products: " + oDb.scalar("SELECT COUNT(DISTINCT Product) FROM Orders")
	oDb.close()

# print rows as a small table: cColumns are the names of the columns to show
func show aRows, aColumns

	for aRow in aRows
		cLine = "   "
		for cColumn in aColumns
			cLine += padRight("" + dbValue(aRow,cColumn),10)
		next
		? cLine
	next
	if len(aRows) = 0
		? "   (no rows)"
	ok

func padRight cText, nWidth

	while len(cText) < nWidth
		cText += " "
	end
	return cText
Output
4 customers and 7 orders are in the database (Dee has no orders)

1. who bought what:
   Ann       Laptop    900       
   Ann       Mouse     20        
   Ann       Monitor   250       
   Bob       Laptop    950       
   Bob       Keyboard  60        
   Cy        Mouse     25        
   Cy        Mouse     25        

2. the total of each customer, the biggest first:
   Ann       3         1170      
   Bob       2         1010      
   Cy        2         50        

3. customers who spent more than 300 (HAVING):
   Ann       1170      
   Bob       1010      
   the same for January only (WHERE first):
   Ann       920       
   Bob       950       

4. every customer with the number of orders (LEFT JOIN keeps Dee):
   Ann       3         
   Bob       2         
   Cy        2         
   Dee       0         

5. the total per city:
   Cairo     1220      
   Oslo      1010      

6. orders above the average (a sub-query calculates the average):
   Laptop    950       
   Laptop    900       

7. the number of different products: 4

How it works#

oDb.sqlRows(sql, parameters) runs any SELECT and returns the rows as lists of [column, value] pairs; dbValue(row, "Total") reads one column. The show helper prints a few columns as a small table.

1. JOIN#

FROM Orders o JOIN Customers c ON c.Id = o.CustomerId puts together each order and the customer whose Id equals its CustomerId. o and c are short aliases of the tables. The result has one row per order, with the customer's name next to it.

2. GROUP BY#

GROUP BY c.Name makes one row per customer; COUNT(o.Id) and SUM(o.Amount) are calculated over the orders of that customer. ORDER BY Total DESC puts the biggest first. Every column in SELECT must be either in GROUP BY or inside an aggregate.

3. WHERE and HAVING#

WHERE removes rows before they are grouped (only the January orders); HAVING removes groups after the totals are known (only customers with a total above 300). A condition on an aggregate can only go in HAVING.

4. LEFT JOIN#

A plain JOIN drops rows that have no partner: Dee does not appear in steps 1–3. LEFT JOIN keeps every row of the left table and fills the missing side with empty values, so COUNT(o.Id) is 0 for Dee. Use it for reports such as "all customers, also those who did not buy".

5. Groups from another table#

The city is in Customers and the amount in Orders; the join lets you total by a column of either.

6. A sub-query#

WHERE Amount > (SELECT AVG(Amount) FROM Orders) first calculates the average (318.57…) and then keeps the larger orders. A query inside a query is fine as long as the inner one returns one value.

7. scalar#

oDb.scalar(sql) returns the first column of the first row — handy for a count or a total.

Warning

Never put values into SQL by adding strings: "... WHERE Month = '" + cMonth + "'" lets a user write SQL into your query (SQL injection). Use the parameters {0}, {1}, … and pass the values in the list, as steps 3 does.

What you learned#

Exercises#

  1. Show the average order per customer, rounded.
  2. List the products that were never ordered by a customer from Cairo.
  3. Find the month with the highest total.
  4. Add a Products table with prices and join it to the orders.

Next#

Entity objects and migrations

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.