首页 > 解决方案 > 按两个值分组

问题描述

您好,我有这张表:(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 │
└──────────────┴──────┴──────┘

标签: mysqlsql

解决方案


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

推荐阅读