Lets say I have four tables:
CREATE TABLE dealers (
id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL
)
CREATE TABLE brands (
id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL
)
CREATE TABLE cars (
id SERIAL PRIMARY KEY,
brand INTEGER REFERENCES (brands.id) NOT NULL,
name TEXT UNIQUE NOT NULL
)
CREATE TABLE sells (
id SERIAL,
dealer INTEGER REFERENCES (dealers.id) NOT NULL,
car INTEGER REFERENCES (cars.id) NOT NULL
)
If n is the number of dealers and m in the number of dealers, how to I create a n x m matrix in sql that displays the number of cars a dealer sells of a brand.
The output should look something like this:
Dealer |Honda Toyota Tesla
CarMax 103 204 1
CheapCars 160 320 0
GoodCars 40 20 2
OCHonda 201 0 0
What is the simplest, most efficient query I can use to accomplish this task?
EDIT: Changed m to be the number of dealers instead of cars