I have to group by the different vendors in each given year by calculating the total sales for those years. I could only get the first column.
Output obtained
query='''
SELECT ven.nombre_vendedor,
SUM(total-costo_envio) AS año2019
FROM itens_pedidos ip
INNER JOIN pedidos ped ON ped.pedido_id=ip.pedido_id
INNER JOIN vendedores ven ON ven.vendedor_id=ped.vendedor_id
WHERE fecha_compra
BETWEEN "2019-01-01" AND "2019-31-12"
GROUP BY ven.nombre_vendedor
LIMIT 5
'''
nombre_vendedor | año_2019 |
---|---|
Ana Duarte | 2154261.6 |
Daniel Siqueira | 2020503.2 |
Millena Pereira | 2054682.4 |
Nadia Oliveira | 2296986.4 |
expected output
nombre_vendedor | año2019 | año2020 | año2021 |
---|---|---|---|
Ana Duarte | 2154261.6 | 5054009.6 | 7154261.6 |
Daniel Siqueira | 2020503.2 | 5254009.6 | 9054261.6 |
Millena Pereira | 2054682.4 | 3854261.6 | 1854261.6 |
Nadia Oliveira | 2296986.4 | 2154261.6 | 4554261.6 |
2
Answers
the total sales for each vendor are grouped by year, you need to use conditional aggregation. your query to include separate sums for each year using
CASE
statements inside theSUM
function.above query will calculate the total sales for each vendor for each year separately using conditional aggregation based on the
fecha_compra
(purchase date). you can to adjust the date ranges in theCASE
statements to match the desired year intervals.