简体   繁体   中英

PHP count values with same id

My current project: I'm trying to create an overview of all cars in a company.

I get the following mysql result table:

|car_id|distance|
|   1  |  33875 |
|   1  |  33027 |
|   1  |  31579 |
|   2  | 125636 |
|   2  | 124937 |

The "Distance" is the mileage after a fill up.

What do I need?

I need the total distance for each car.

The result should look like:

|car_id|distance|
|   1  |  2296  | (33875 - 31579)
|   2  |   699  | (125636 - 124937)

You can easily do it with group by clause, eg:

SELECT id, (MAX(distance) - MIN(distance)) AS mileage
FROM cars
GROUP BY id;

Here's the SQL Fiddle .

Adding to Darshan's answer:

select id, (max(distance) - min(distance)) as mileage
, concat('(',min(distance),' - ',max(distance),')') as distance
from cars
group by id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM