mysql - 按两个值分组
问题描述
您好,我有这张表:(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
推荐阅读
- swift - 使用背景颜色向 UILabel 添加填充
- python-3.x - 使用乘法多次打印字符串的问题
- arrays - C中有效函数和数组的问题
- vb.net - CSV 到 DataTable 将浮点值解析为日期
- javascript - DirectionalLightHelper 和 CameraHelper 之间的问题是否会导致场景阴影出现问题?
- python - Pandas Dataframe 同时拆分列列表
- excel - 在 powershell 中使用 excel com 对象提取单元格值的问题
- akamai - 在 akamai.EdgeHostName 中指定 IPv4 和 IPv6 IP 类型
- spring-boot - 是否可以使用 OidcUserRequest 获取刷新令牌?
- firebase - 您可以在尚未构建的移动应用上使用 Firebase 吗?