【发布时间】:2025-11-29 17:00:02
【问题描述】:
我正在尝试在我的 sql 代码中计算 efficiency,这需要将 2 个变量 vehicle_dispatched 和 available_cars 相除,但它为整列返回相同的答案。这是我的sql代码:
SELECT *,@vehicles_dispatched:=COUNT(DISTINCT v.vehicle_id) AS vehicles_dispatched,
@available_cars:=(SELECT COUNT(vehicle_id) FROM vehicles WHERE company_id=1) AS available_cars,
FORMAT(@vehicles_dispatched / @available_cars,2) AS efficiency
FROM driver_attendance da
LEFT JOIN vehicles v ON v.vehicle_id=da.vehicle_id
LEFT JOIN collection co ON co.driver_attendance_id=da.driver_attendance_id
LEFT JOIN collectible cb ON cb.collectible_id = co.collectible_id
WHERE company_id=1 GROUP BY attendance_date DESC
示例输出:
vehicles_dispatched available_cars efficiency
5 7 0.14
3 7 0.14
6 7 0.14
1 7 0.14
问题是整列都有相同的答案,而不是对每一行进行除法。
这里是更新后的查询,它提供了我想要的输出,这一切都归功于@Ravinder。
SELECT *,FORMAT( vehicle_dispatched / available_cars, 2 ) AS efficiency
FROM(
SELECT da.*,
SUM(CASE WHEN attendance_status = 4 THEN 1 ELSE 0 END) AS total_cars_collectible,
SUM(boundary_payment)+SUM(deficit_payment) AS total_daily_collection,
((SUM(boundary_due)+SUM(boundary_deficit)) - (SUM(boundary_payment)+SUM(deficit_payment))) AS total_short,
@cars_in_maintenance:=(SELECT SUM(DISTINCT(CASE WHEN vehicle_on_duty=2 THEN 1 ELSE 0 END)) AS cars_under_maintenance FROM vehicles WHERE company_id=84) AS cars_in_maintenance,
@vehicle_dispatched:=COUNT(DISTINCT v.vehicle_id) AS vehicle_dispatched,
@available_cars:=(SELECT COUNT(vehicle_id) FROM vehicles WHERE company_id=84) AS available_cars
FROM driver_attendance da
LEFT JOIN vehicles v ON v.vehicle_id = da.vehicle_id
LEFT JOIN collection co ON co.driver_attendance_id = da.driver_attendance_id
LEFT JOIN collectible cb ON cb.collectible_id = co.collectible_id
WHERE v.company_id = 84
GROUP BY da.attendance_date DESC
) AS vehicles_attended
【问题讨论】:
-
在
vehicles表中,vehicle_id是主键还是外键?因为,如果primary,则不需要distinct vehicle_id。 -
它是一个主键,但是当
LEFT JOIN与driver_attendance一起使用时有重复的情况,因此我使用了DISTINCT
标签: mysql