按两个值分组

蓝光

您好,我有这张表:(id、carId、gasStationId、liters、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 │ 
└─────────────── ┴──────┴──────┘
拉西尔·希兰

是一样的,只是添加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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章