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.
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;| titulo | facturacion_euros | unidades_vendidas | numero_pedidos |
|---|---|---|---|
| Pixel de Medianoche | 160 | 8 | 4 |
| Ritmo de Neón | 135 | 9 | 3 |
| Niebla en Marte | 135 | 3 | 2 |
| Islas de Silicio | 90 | 3 | 2 |
| Bosque Binario | 70 | 2 | 2 |
| Órbita de Cobre | 60 | 1 | 1 |
| Laberinto Lunar | 50 | 1 | 1 |
| Mareas de Datos | 0 | 0 | 0 |