0

Hello I have this table: (id, carId, gasStationId, liters, totalPrice). I would like to create query for sum total costs in each gas stations by car. I know how to sum total costs by gas station, but I don't know how to group by car. Here is my query:

select sum(totalPrice) as totalCosts
     , count(*) as countPurchases
     , g.name
     , p.carId 
  from purchase as p
  join gas_station as g  
    on g.id = p.id
 group 
    by gasStationId

I would like get this result:

┌─────────────┬──────┬──────┐
│ GasStation1 │ Car1 │ 1000 │
├─────────────┼──────┼──────┤
│ GasStation1 │ Car2 │ 1500 │
│ GasStation2 │ Car2 │  500 │
│ GasStation2 │ Car1 │  700 │
└─────────────┴──────┴──────┘
3
  • 1
    Do you mean something like group by gasStationId, carId or are you wanting to join another table you're not showing? Commented Dec 10, 2018 at 17:48
  • 1
    You can group by more than 1 field. Commented Dec 10, 2018 at 17:49
  • Side note: Why do you have gasStationId in your grouping? It looks like it should've been g.id. But I following your query in my answer. Commented Dec 10, 2018 at 17:57

2 Answers 2

1

It's the same thing, just add p.carId to the grouping separated by a comma:

GROUP BY gasStationId, p.carId

So for the results in your question, you can do:

SELECT g.name, p.carId, SUM(totalPrice) AS totalCosts
FROM purchase AS p
JOIN gas_station AS g ON g.id = p.id
GROUP BY gasStationId, p.carId
Sign up to request clarification or add additional context in comments.

Comments

0

A good idea is to use window functions: https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html

something like:

SELECT
     gasStationId,
     SUM(totalPrice) OVER(PARTITION BY carId) AS price_by_car
   FROM purchase p
   JOIN gasStations g
   ON g.id=p.gassStationId;

2 Comments

Where did you get profit from? And in the output example, the OP has one total, not two.
I'll fix it. Just added the total per station for completeness.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.