按两个值分组

时间:2018-12-10 17:46:03

标签: mysql sql

您好,我有此表:(id,carId,gasStationId,升,totalPrice)。我想创建每个汽车加油站的总费用查询。我知道如何将加油站的总成本相加,但不知道如何按汽车分组。 这是我的查询:

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

我想得到这个结果:

┌─────────────┬──────┬──────┐
│ GasStation1 │ Car1 │ 1000 │
├─────────────┼──────┼──────┤
│ GasStation1 │ Car2 │ 1500 │
│ GasStation2 │ Car2 │  500 │
│ GasStation2 │ Car1 │  700 │
└─────────────┴──────┴──────┘

2 个答案:

答案 0 :(得分:1)

是同一回事,只需将p.carId添加到以逗号分隔的分组中即可:

GROUP BY gasStationId, p.carId

因此,对于您的问题,您可以执行以下操作:

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

答案 1 :(得分:0)

一个好主意是使用窗口函数:https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html

类似:

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