LEFT JOIN · COALESCE

Rank the games by revenue

Rank the games by revenue. Show the number of copies sold and the number of orders for each game, including games with no sales.

SQLite
RESULTSReady to run
Compare with the solution

Pixel de Medianoche leads with €160 in revenue. Mareas de Datos stays in the catalog at €0.

SELECT v.titulo,
       COALESCE(SUM(lp.unidades * lp.precio_unitario_euros), 0) AS facturacion_euros,
       COALESCE(SUM(lp.unidades), 0) AS unidades_vendidas,
       COUNT(DISTINCT p.id) AS numero_pedidos
FROM videojuegos AS v
LEFT JOIN lineas_pedido AS lp ON lp.videojuego_id = v.id
LEFT JOIN pedidos AS p ON p.id = lp.pedido_id
GROUP BY v.id, v.titulo
ORDER BY facturacion_euros DESC, unidades_vendidas DESC, v.titulo ASC;
titulofacturacion_eurosunidades_vendidasnumero_pedidos
Pixel de Medianoche16084
Ritmo de Neón13593
Niebla en Marte13532
Islas de Silicio9032
Bosque Binario7022
Órbita de Cobre6011
Laberinto Lunar5011
Mareas de Datos000