按两个值分组

f87krz0w  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(218)

您好,我有这张table:(id,carid,gasstationid,升,总价)。我想创建查询的总和总成本在每个加油站的汽车。我知道如何按加油站计算总费用,但我不知道如何按汽车分组。我的问题是:

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 │
└─────────────┴──────┴──────┘
wa7juj8i

wa7juj8i1#

是一样的,只要加上 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
qvk1mo1f

qvk1mo1f2#

一个好主意是使用窗口函数: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;

相关问题